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

1.344   ! brouard     1: /* $Id: imach.c,v 1.343 2022/09/14 14:22:16 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.344   ! brouard     4:   Revision 1.343  2022/09/14 14:22:16  brouard
        !             5:   Summary: version 0.99r39
        !             6: 
        !             7:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
        !             8:   (fixed or time varying), using new last columns of
        !             9:   ILK_parameter.txt file.
        !            10: 
1.343     brouard    11:   Revision 1.342  2022/09/11 19:54:09  brouard
                     12:   Summary: 0.99r38
                     13: 
                     14:   * imach.c (Module): Adding timevarying products of any kinds,
                     15:   should work before shifting cotvar from ncovcol+nqv columns in
                     16:   order to have a correspondance between the column of cotvar and
                     17:   the id of column.
                     18:   (Module): Some cleaning and adding covariates in ILK.txt
                     19: 
1.342     brouard    20:   Revision 1.341  2022/09/11 07:58:42  brouard
                     21:   Summary: Version 0.99r38
                     22: 
                     23:   After adding change in cotvar.
                     24: 
1.341     brouard    25:   Revision 1.340  2022/09/11 07:53:11  brouard
                     26:   Summary: Version imach 0.99r37
                     27: 
                     28:   * imach.c (Module): Adding timevarying products of any kinds,
                     29:   should work before shifting cotvar from ncovcol+nqv columns in
                     30:   order to have a correspondance between the column of cotvar and
                     31:   the id of column.
                     32: 
1.340     brouard    33:   Revision 1.339  2022/09/09 17:55:22  brouard
                     34:   Summary: version 0.99r37
                     35: 
                     36:   * imach.c (Module): Many improvements for fixing products of fixed
                     37:   timevarying as well as fixed * fixed, and test with quantitative
                     38:   covariate.
                     39: 
1.339     brouard    40:   Revision 1.338  2022/09/04 17:40:33  brouard
                     41:   Summary: 0.99r36
                     42: 
                     43:   * imach.c (Module): Now the easy runs i.e. without result or
                     44:   model=1+age only did not work. The defautl combination should be 1
                     45:   and not 0 because everything hasn't been tranformed yet.
                     46: 
1.338     brouard    47:   Revision 1.337  2022/09/02 14:26:02  brouard
                     48:   Summary: version 0.99r35
                     49: 
                     50:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     51:   1+age+V1+V1*age for females and 1+age for females only
                     52:   (education=1 noweight)
                     53: 
1.337     brouard    54:   Revision 1.336  2022/08/31 09:52:36  brouard
                     55:   *** empty log message ***
                     56: 
1.336     brouard    57:   Revision 1.335  2022/08/31 08:23:16  brouard
                     58:   Summary: improvements...
                     59: 
1.335     brouard    60:   Revision 1.334  2022/08/25 09:08:41  brouard
                     61:   Summary: In progress for quantitative
                     62: 
1.334     brouard    63:   Revision 1.333  2022/08/21 09:10:30  brouard
                     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.333     brouard    82:   Revision 1.332  2022/08/21 09:06:25  brouard
                     83:   Summary: Version 0.99r33
                     84: 
                     85:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     86:   reassigning covariates: my first idea was that people will always
                     87:   use the first covariate V1 into the model but in fact they are
                     88:   producing data with many covariates and can use an equation model
                     89:   with some of the covariate; it means that in a model V2+V3 instead
                     90:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     91:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     92:   the equation model is restricted to two variables only (V2, V3)
                     93:   and the combination for V2 should be codtabm(k,1) instead of
                     94:   (codtabm(k,2), and the code should be
                     95:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     96:   made. All of these should be simplified once a day like we did in
                     97:   hpxij() for example by using precov[nres] which is computed in
                     98:   decoderesult for each nres of each resultline. Loop should be done
                     99:   on the equation model globally by distinguishing only product with
                    100:   age (which are changing with age) and no more on type of
                    101:   covariates, single dummies, single covariates.
                    102: 
1.332     brouard   103:   Revision 1.331  2022/08/07 05:40:09  brouard
                    104:   *** empty log message ***
                    105: 
1.331     brouard   106:   Revision 1.330  2022/08/06 07:18:25  brouard
                    107:   Summary: last 0.99r31
                    108: 
                    109:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    110: 
1.330     brouard   111:   Revision 1.329  2022/08/03 17:29:54  brouard
                    112:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    113: 
1.329     brouard   114:   Revision 1.328  2022/07/27 17:40:48  brouard
                    115:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    116: 
1.328     brouard   117:   Revision 1.327  2022/07/27 14:47:35  brouard
                    118:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    119: 
1.327     brouard   120:   Revision 1.326  2022/07/26 17:33:55  brouard
                    121:   Summary: some test with nres=1
                    122: 
1.326     brouard   123:   Revision 1.325  2022/07/25 14:27:23  brouard
                    124:   Summary: r30
                    125: 
                    126:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    127:   coredumped, revealed by Feiuno, thank you.
                    128: 
1.325     brouard   129:   Revision 1.324  2022/07/23 17:44:26  brouard
                    130:   *** empty log message ***
                    131: 
1.324     brouard   132:   Revision 1.323  2022/07/22 12:30:08  brouard
                    133:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    134: 
1.323     brouard   135:   Revision 1.322  2022/07/22 12:27:48  brouard
                    136:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    137: 
1.322     brouard   138:   Revision 1.321  2022/07/22 12:04:24  brouard
                    139:   Summary: r28
                    140: 
                    141:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    142: 
1.321     brouard   143:   Revision 1.320  2022/06/02 05:10:11  brouard
                    144:   *** empty log message ***
                    145: 
1.320     brouard   146:   Revision 1.319  2022/06/02 04:45:11  brouard
                    147:   * imach.c (Module): Adding the Wald tests from the log to the main
                    148:   htm for better display of the maximum likelihood estimators.
                    149: 
1.319     brouard   150:   Revision 1.318  2022/05/24 08:10:59  brouard
                    151:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    152:   of confidencce intervals with product in the equation modelC
                    153: 
1.318     brouard   154:   Revision 1.317  2022/05/15 15:06:23  brouard
                    155:   * imach.c (Module):  Some minor improvements
                    156: 
1.317     brouard   157:   Revision 1.316  2022/05/11 15:11:31  brouard
                    158:   Summary: r27
                    159: 
1.316     brouard   160:   Revision 1.315  2022/05/11 15:06:32  brouard
                    161:   *** empty log message ***
                    162: 
1.315     brouard   163:   Revision 1.314  2022/04/13 17:43:09  brouard
                    164:   * imach.c (Module): Adding link to text data files
                    165: 
1.314     brouard   166:   Revision 1.313  2022/04/11 15:57:42  brouard
                    167:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    168: 
1.313     brouard   169:   Revision 1.312  2022/04/05 21:24:39  brouard
                    170:   *** empty log message ***
                    171: 
1.312     brouard   172:   Revision 1.311  2022/04/05 21:03:51  brouard
                    173:   Summary: Fixed quantitative covariates
                    174: 
                    175:          Fixed covariates (dummy or quantitative)
                    176:        with missing values have never been allowed but are ERRORS and
                    177:        program quits. Standard deviations of fixed covariates were
                    178:        wrongly computed. Mean and standard deviations of time varying
                    179:        covariates are still not computed.
                    180: 
1.311     brouard   181:   Revision 1.310  2022/03/17 08:45:53  brouard
                    182:   Summary: 99r25
                    183: 
                    184:   Improving detection of errors: result lines should be compatible with
                    185:   the model.
                    186: 
1.310     brouard   187:   Revision 1.309  2021/05/20 12:39:14  brouard
                    188:   Summary: Version 0.99r24
                    189: 
1.309     brouard   190:   Revision 1.308  2021/03/31 13:11:57  brouard
                    191:   Summary: Version 0.99r23
                    192: 
                    193: 
                    194:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    195: 
1.308     brouard   196:   Revision 1.307  2021/03/08 18:11:32  brouard
                    197:   Summary: 0.99r22 fixed bug on result:
                    198: 
1.307     brouard   199:   Revision 1.306  2021/02/20 15:44:02  brouard
                    200:   Summary: Version 0.99r21
                    201: 
                    202:   * imach.c (Module): Fix bug on quitting after result lines!
                    203:   (Module): Version 0.99r21
                    204: 
1.306     brouard   205:   Revision 1.305  2021/02/20 15:28:30  brouard
                    206:   * imach.c (Module): Fix bug on quitting after result lines!
                    207: 
1.305     brouard   208:   Revision 1.304  2021/02/12 11:34:20  brouard
                    209:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    210: 
1.304     brouard   211:   Revision 1.303  2021/02/11 19:50:15  brouard
                    212:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    213: 
1.303     brouard   214:   Revision 1.302  2020/02/22 21:00:05  brouard
                    215:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    216:   and life table from the data without any state)
                    217: 
1.302     brouard   218:   Revision 1.301  2019/06/04 13:51:20  brouard
                    219:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    220: 
1.301     brouard   221:   Revision 1.300  2019/05/22 19:09:45  brouard
                    222:   Summary: version 0.99r19 of May 2019
                    223: 
1.300     brouard   224:   Revision 1.299  2019/05/22 18:37:08  brouard
                    225:   Summary: Cleaned 0.99r19
                    226: 
1.299     brouard   227:   Revision 1.298  2019/05/22 18:19:56  brouard
                    228:   *** empty log message ***
                    229: 
1.298     brouard   230:   Revision 1.297  2019/05/22 17:56:10  brouard
                    231:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    232: 
1.297     brouard   233:   Revision 1.296  2019/05/20 13:03:18  brouard
                    234:   Summary: Projection syntax simplified
                    235: 
                    236: 
                    237:   We can now start projections, forward or backward, from the mean date
                    238:   of inteviews up to or down to a number of years of projection:
                    239:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    240:   or
                    241:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    242:   or
                    243:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    244:   or
                    245:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    246: 
1.296     brouard   247:   Revision 1.295  2019/05/18 09:52:50  brouard
                    248:   Summary: doxygen tex bug
                    249: 
1.295     brouard   250:   Revision 1.294  2019/05/16 14:54:33  brouard
                    251:   Summary: There was some wrong lines added
                    252: 
1.294     brouard   253:   Revision 1.293  2019/05/09 15:17:34  brouard
                    254:   *** empty log message ***
                    255: 
1.293     brouard   256:   Revision 1.292  2019/05/09 14:17:20  brouard
                    257:   Summary: Some updates
                    258: 
1.292     brouard   259:   Revision 1.291  2019/05/09 13:44:18  brouard
                    260:   Summary: Before ncovmax
                    261: 
1.291     brouard   262:   Revision 1.290  2019/05/09 13:39:37  brouard
                    263:   Summary: 0.99r18 unlimited number of individuals
                    264: 
                    265:   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.
                    266: 
1.290     brouard   267:   Revision 1.289  2018/12/13 09:16:26  brouard
                    268:   Summary: Bug for young ages (<-30) will be in r17
                    269: 
1.289     brouard   270:   Revision 1.288  2018/05/02 20:58:27  brouard
                    271:   Summary: Some bugs fixed
                    272: 
1.288     brouard   273:   Revision 1.287  2018/05/01 17:57:25  brouard
                    274:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    275: 
1.287     brouard   276:   Revision 1.286  2018/04/27 14:27:04  brouard
                    277:   Summary: some minor bugs
                    278: 
1.286     brouard   279:   Revision 1.285  2018/04/21 21:02:16  brouard
                    280:   Summary: Some bugs fixed, valgrind tested
                    281: 
1.285     brouard   282:   Revision 1.284  2018/04/20 05:22:13  brouard
                    283:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    284: 
1.284     brouard   285:   Revision 1.283  2018/04/19 14:49:16  brouard
                    286:   Summary: Some minor bugs fixed
                    287: 
1.283     brouard   288:   Revision 1.282  2018/02/27 22:50:02  brouard
                    289:   *** empty log message ***
                    290: 
1.282     brouard   291:   Revision 1.281  2018/02/27 19:25:23  brouard
                    292:   Summary: Adding second argument for quitting
                    293: 
1.281     brouard   294:   Revision 1.280  2018/02/21 07:58:13  brouard
                    295:   Summary: 0.99r15
                    296: 
                    297:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    298: 
1.280     brouard   299:   Revision 1.279  2017/07/20 13:35:01  brouard
                    300:   Summary: temporary working
                    301: 
1.279     brouard   302:   Revision 1.278  2017/07/19 14:09:02  brouard
                    303:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    304: 
1.278     brouard   305:   Revision 1.277  2017/07/17 08:53:49  brouard
                    306:   Summary: BOM files can be read now
                    307: 
1.277     brouard   308:   Revision 1.276  2017/06/30 15:48:31  brouard
                    309:   Summary: Graphs improvements
                    310: 
1.276     brouard   311:   Revision 1.275  2017/06/30 13:39:33  brouard
                    312:   Summary: Saito's color
                    313: 
1.275     brouard   314:   Revision 1.274  2017/06/29 09:47:08  brouard
                    315:   Summary: Version 0.99r14
                    316: 
1.274     brouard   317:   Revision 1.273  2017/06/27 11:06:02  brouard
                    318:   Summary: More documentation on projections
                    319: 
1.273     brouard   320:   Revision 1.272  2017/06/27 10:22:40  brouard
                    321:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    322: 
1.272     brouard   323:   Revision 1.271  2017/06/27 10:17:50  brouard
                    324:   Summary: Some bug with rint
                    325: 
1.271     brouard   326:   Revision 1.270  2017/05/24 05:45:29  brouard
                    327:   *** empty log message ***
                    328: 
1.270     brouard   329:   Revision 1.269  2017/05/23 08:39:25  brouard
                    330:   Summary: Code into subroutine, cleanings
                    331: 
1.269     brouard   332:   Revision 1.268  2017/05/18 20:09:32  brouard
                    333:   Summary: backprojection and confidence intervals of backprevalence
                    334: 
1.268     brouard   335:   Revision 1.267  2017/05/13 10:25:05  brouard
                    336:   Summary: temporary save for backprojection
                    337: 
1.267     brouard   338:   Revision 1.266  2017/05/13 07:26:12  brouard
                    339:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    340: 
1.266     brouard   341:   Revision 1.265  2017/04/26 16:22:11  brouard
                    342:   Summary: imach 0.99r13 Some bugs fixed
                    343: 
1.265     brouard   344:   Revision 1.264  2017/04/26 06:01:29  brouard
                    345:   Summary: Labels in graphs
                    346: 
1.264     brouard   347:   Revision 1.263  2017/04/24 15:23:15  brouard
                    348:   Summary: to save
                    349: 
1.263     brouard   350:   Revision 1.262  2017/04/18 16:48:12  brouard
                    351:   *** empty log message ***
                    352: 
1.262     brouard   353:   Revision 1.261  2017/04/05 10:14:09  brouard
                    354:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    355: 
1.261     brouard   356:   Revision 1.260  2017/04/04 17:46:59  brouard
                    357:   Summary: Gnuplot indexations fixed (humm)
                    358: 
1.260     brouard   359:   Revision 1.259  2017/04/04 13:01:16  brouard
                    360:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    361: 
1.259     brouard   362:   Revision 1.258  2017/04/03 10:17:47  brouard
                    363:   Summary: Version 0.99r12
                    364: 
                    365:   Some cleanings, conformed with updated documentation.
                    366: 
1.258     brouard   367:   Revision 1.257  2017/03/29 16:53:30  brouard
                    368:   Summary: Temp
                    369: 
1.257     brouard   370:   Revision 1.256  2017/03/27 05:50:23  brouard
                    371:   Summary: Temporary
                    372: 
1.256     brouard   373:   Revision 1.255  2017/03/08 16:02:28  brouard
                    374:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    375: 
1.255     brouard   376:   Revision 1.254  2017/03/08 07:13:00  brouard
                    377:   Summary: Fixing data parameter line
                    378: 
1.254     brouard   379:   Revision 1.253  2016/12/15 11:59:41  brouard
                    380:   Summary: 0.99 in progress
                    381: 
1.253     brouard   382:   Revision 1.252  2016/09/15 21:15:37  brouard
                    383:   *** empty log message ***
                    384: 
1.252     brouard   385:   Revision 1.251  2016/09/15 15:01:13  brouard
                    386:   Summary: not working
                    387: 
1.251     brouard   388:   Revision 1.250  2016/09/08 16:07:27  brouard
                    389:   Summary: continue
                    390: 
1.250     brouard   391:   Revision 1.249  2016/09/07 17:14:18  brouard
                    392:   Summary: Starting values from frequencies
                    393: 
1.249     brouard   394:   Revision 1.248  2016/09/07 14:10:18  brouard
                    395:   *** empty log message ***
                    396: 
1.248     brouard   397:   Revision 1.247  2016/09/02 11:11:21  brouard
                    398:   *** empty log message ***
                    399: 
1.247     brouard   400:   Revision 1.246  2016/09/02 08:49:22  brouard
                    401:   *** empty log message ***
                    402: 
1.246     brouard   403:   Revision 1.245  2016/09/02 07:25:01  brouard
                    404:   *** empty log message ***
                    405: 
1.245     brouard   406:   Revision 1.244  2016/09/02 07:17:34  brouard
                    407:   *** empty log message ***
                    408: 
1.244     brouard   409:   Revision 1.243  2016/09/02 06:45:35  brouard
                    410:   *** empty log message ***
                    411: 
1.243     brouard   412:   Revision 1.242  2016/08/30 15:01:20  brouard
                    413:   Summary: Fixing a lots
                    414: 
1.242     brouard   415:   Revision 1.241  2016/08/29 17:17:25  brouard
                    416:   Summary: gnuplot problem in Back projection to fix
                    417: 
1.241     brouard   418:   Revision 1.240  2016/08/29 07:53:18  brouard
                    419:   Summary: Better
                    420: 
1.240     brouard   421:   Revision 1.239  2016/08/26 15:51:03  brouard
                    422:   Summary: Improvement in Powell output in order to copy and paste
                    423: 
                    424:   Author:
                    425: 
1.239     brouard   426:   Revision 1.238  2016/08/26 14:23:35  brouard
                    427:   Summary: Starting tests of 0.99
                    428: 
1.238     brouard   429:   Revision 1.237  2016/08/26 09:20:19  brouard
                    430:   Summary: to valgrind
                    431: 
1.237     brouard   432:   Revision 1.236  2016/08/25 10:50:18  brouard
                    433:   *** empty log message ***
                    434: 
1.236     brouard   435:   Revision 1.235  2016/08/25 06:59:23  brouard
                    436:   *** empty log message ***
                    437: 
1.235     brouard   438:   Revision 1.234  2016/08/23 16:51:20  brouard
                    439:   *** empty log message ***
                    440: 
1.234     brouard   441:   Revision 1.233  2016/08/23 07:40:50  brouard
                    442:   Summary: not working
                    443: 
1.233     brouard   444:   Revision 1.232  2016/08/22 14:20:21  brouard
                    445:   Summary: not working
                    446: 
1.232     brouard   447:   Revision 1.231  2016/08/22 07:17:15  brouard
                    448:   Summary: not working
                    449: 
1.231     brouard   450:   Revision 1.230  2016/08/22 06:55:53  brouard
                    451:   Summary: Not working
                    452: 
1.230     brouard   453:   Revision 1.229  2016/07/23 09:45:53  brouard
                    454:   Summary: Completing for func too
                    455: 
1.229     brouard   456:   Revision 1.228  2016/07/22 17:45:30  brouard
                    457:   Summary: Fixing some arrays, still debugging
                    458: 
1.227     brouard   459:   Revision 1.226  2016/07/12 18:42:34  brouard
                    460:   Summary: temp
                    461: 
1.226     brouard   462:   Revision 1.225  2016/07/12 08:40:03  brouard
                    463:   Summary: saving but not running
                    464: 
1.225     brouard   465:   Revision 1.224  2016/07/01 13:16:01  brouard
                    466:   Summary: Fixes
                    467: 
1.224     brouard   468:   Revision 1.223  2016/02/19 09:23:35  brouard
                    469:   Summary: temporary
                    470: 
1.223     brouard   471:   Revision 1.222  2016/02/17 08:14:50  brouard
                    472:   Summary: Probably last 0.98 stable version 0.98r6
                    473: 
1.222     brouard   474:   Revision 1.221  2016/02/15 23:35:36  brouard
                    475:   Summary: minor bug
                    476: 
1.220     brouard   477:   Revision 1.219  2016/02/15 00:48:12  brouard
                    478:   *** empty log message ***
                    479: 
1.219     brouard   480:   Revision 1.218  2016/02/12 11:29:23  brouard
                    481:   Summary: 0.99 Back projections
                    482: 
1.218     brouard   483:   Revision 1.217  2015/12/23 17:18:31  brouard
                    484:   Summary: Experimental backcast
                    485: 
1.217     brouard   486:   Revision 1.216  2015/12/18 17:32:11  brouard
                    487:   Summary: 0.98r4 Warning and status=-2
                    488: 
                    489:   Version 0.98r4 is now:
                    490:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    491:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    492:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    493: 
1.216     brouard   494:   Revision 1.215  2015/12/16 08:52:24  brouard
                    495:   Summary: 0.98r4 working
                    496: 
1.215     brouard   497:   Revision 1.214  2015/12/16 06:57:54  brouard
                    498:   Summary: temporary not working
                    499: 
1.214     brouard   500:   Revision 1.213  2015/12/11 18:22:17  brouard
                    501:   Summary: 0.98r4
                    502: 
1.213     brouard   503:   Revision 1.212  2015/11/21 12:47:24  brouard
                    504:   Summary: minor typo
                    505: 
1.212     brouard   506:   Revision 1.211  2015/11/21 12:41:11  brouard
                    507:   Summary: 0.98r3 with some graph of projected cross-sectional
                    508: 
                    509:   Author: Nicolas Brouard
                    510: 
1.211     brouard   511:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   512:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   513:   Summary: Adding ftolpl parameter
                    514:   Author: N Brouard
                    515: 
                    516:   We had difficulties to get smoothed confidence intervals. It was due
                    517:   to the period prevalence which wasn't computed accurately. The inner
                    518:   parameter ftolpl is now an outer parameter of the .imach parameter
                    519:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    520:   computation are long.
                    521: 
1.209     brouard   522:   Revision 1.208  2015/11/17 14:31:57  brouard
                    523:   Summary: temporary
                    524: 
1.208     brouard   525:   Revision 1.207  2015/10/27 17:36:57  brouard
                    526:   *** empty log message ***
                    527: 
1.207     brouard   528:   Revision 1.206  2015/10/24 07:14:11  brouard
                    529:   *** empty log message ***
                    530: 
1.206     brouard   531:   Revision 1.205  2015/10/23 15:50:53  brouard
                    532:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    533: 
1.205     brouard   534:   Revision 1.204  2015/10/01 16:20:26  brouard
                    535:   Summary: Some new graphs of contribution to likelihood
                    536: 
1.204     brouard   537:   Revision 1.203  2015/09/30 17:45:14  brouard
                    538:   Summary: looking at better estimation of the hessian
                    539: 
                    540:   Also a better criteria for convergence to the period prevalence And
                    541:   therefore adding the number of years needed to converge. (The
                    542:   prevalence in any alive state shold sum to one
                    543: 
1.203     brouard   544:   Revision 1.202  2015/09/22 19:45:16  brouard
                    545:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    546: 
1.202     brouard   547:   Revision 1.201  2015/09/15 17:34:58  brouard
                    548:   Summary: 0.98r0
                    549: 
                    550:   - Some new graphs like suvival functions
                    551:   - Some bugs fixed like model=1+age+V2.
                    552: 
1.201     brouard   553:   Revision 1.200  2015/09/09 16:53:55  brouard
                    554:   Summary: Big bug thanks to Flavia
                    555: 
                    556:   Even model=1+age+V2. did not work anymore
                    557: 
1.200     brouard   558:   Revision 1.199  2015/09/07 14:09:23  brouard
                    559:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    560: 
1.199     brouard   561:   Revision 1.198  2015/09/03 07:14:39  brouard
                    562:   Summary: 0.98q5 Flavia
                    563: 
1.198     brouard   564:   Revision 1.197  2015/09/01 18:24:39  brouard
                    565:   *** empty log message ***
                    566: 
1.197     brouard   567:   Revision 1.196  2015/08/18 23:17:52  brouard
                    568:   Summary: 0.98q5
                    569: 
1.196     brouard   570:   Revision 1.195  2015/08/18 16:28:39  brouard
                    571:   Summary: Adding a hack for testing purpose
                    572: 
                    573:   After reading the title, ftol and model lines, if the comment line has
                    574:   a q, starting with #q, the answer at the end of the run is quit. It
                    575:   permits to run test files in batch with ctest. The former workaround was
                    576:   $ echo q | imach foo.imach
                    577: 
1.195     brouard   578:   Revision 1.194  2015/08/18 13:32:00  brouard
                    579:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    580: 
1.194     brouard   581:   Revision 1.193  2015/08/04 07:17:42  brouard
                    582:   Summary: 0.98q4
                    583: 
1.193     brouard   584:   Revision 1.192  2015/07/16 16:49:02  brouard
                    585:   Summary: Fixing some outputs
                    586: 
1.192     brouard   587:   Revision 1.191  2015/07/14 10:00:33  brouard
                    588:   Summary: Some fixes
                    589: 
1.191     brouard   590:   Revision 1.190  2015/05/05 08:51:13  brouard
                    591:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    592: 
                    593:   Fix 1+age+.
                    594: 
1.190     brouard   595:   Revision 1.189  2015/04/30 14:45:16  brouard
                    596:   Summary: 0.98q2
                    597: 
1.189     brouard   598:   Revision 1.188  2015/04/30 08:27:53  brouard
                    599:   *** empty log message ***
                    600: 
1.188     brouard   601:   Revision 1.187  2015/04/29 09:11:15  brouard
                    602:   *** empty log message ***
                    603: 
1.187     brouard   604:   Revision 1.186  2015/04/23 12:01:52  brouard
                    605:   Summary: V1*age is working now, version 0.98q1
                    606: 
                    607:   Some codes had been disabled in order to simplify and Vn*age was
                    608:   working in the optimization phase, ie, giving correct MLE parameters,
                    609:   but, as usual, outputs were not correct and program core dumped.
                    610: 
1.186     brouard   611:   Revision 1.185  2015/03/11 13:26:42  brouard
                    612:   Summary: Inclusion of compile and links command line for Intel Compiler
                    613: 
1.185     brouard   614:   Revision 1.184  2015/03/11 11:52:39  brouard
                    615:   Summary: Back from Windows 8. Intel Compiler
                    616: 
1.184     brouard   617:   Revision 1.183  2015/03/10 20:34:32  brouard
                    618:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    619: 
                    620:   We use directest instead of original Powell test; probably no
                    621:   incidence on the results, but better justifications;
                    622:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    623:   wrong results.
                    624: 
1.183     brouard   625:   Revision 1.182  2015/02/12 08:19:57  brouard
                    626:   Summary: Trying to keep directest which seems simpler and more general
                    627:   Author: Nicolas Brouard
                    628: 
1.182     brouard   629:   Revision 1.181  2015/02/11 23:22:24  brouard
                    630:   Summary: Comments on Powell added
                    631: 
                    632:   Author:
                    633: 
1.181     brouard   634:   Revision 1.180  2015/02/11 17:33:45  brouard
                    635:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    636: 
1.180     brouard   637:   Revision 1.179  2015/01/04 09:57:06  brouard
                    638:   Summary: back to OS/X
                    639: 
1.179     brouard   640:   Revision 1.178  2015/01/04 09:35:48  brouard
                    641:   *** empty log message ***
                    642: 
1.178     brouard   643:   Revision 1.177  2015/01/03 18:40:56  brouard
                    644:   Summary: Still testing ilc32 on OSX
                    645: 
1.177     brouard   646:   Revision 1.176  2015/01/03 16:45:04  brouard
                    647:   *** empty log message ***
                    648: 
1.176     brouard   649:   Revision 1.175  2015/01/03 16:33:42  brouard
                    650:   *** empty log message ***
                    651: 
1.175     brouard   652:   Revision 1.174  2015/01/03 16:15:49  brouard
                    653:   Summary: Still in cross-compilation
                    654: 
1.174     brouard   655:   Revision 1.173  2015/01/03 12:06:26  brouard
                    656:   Summary: trying to detect cross-compilation
                    657: 
1.173     brouard   658:   Revision 1.172  2014/12/27 12:07:47  brouard
                    659:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    660: 
1.172     brouard   661:   Revision 1.171  2014/12/23 13:26:59  brouard
                    662:   Summary: Back from Visual C
                    663: 
                    664:   Still problem with utsname.h on Windows
                    665: 
1.171     brouard   666:   Revision 1.170  2014/12/23 11:17:12  brouard
                    667:   Summary: Cleaning some \%% back to %%
                    668: 
                    669:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    670: 
1.170     brouard   671:   Revision 1.169  2014/12/22 23:08:31  brouard
                    672:   Summary: 0.98p
                    673: 
                    674:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    675: 
1.169     brouard   676:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   677:   Summary: update
1.169     brouard   678: 
1.168     brouard   679:   Revision 1.167  2014/12/22 13:50:56  brouard
                    680:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    681: 
                    682:   Testing on Linux 64
                    683: 
1.167     brouard   684:   Revision 1.166  2014/12/22 11:40:47  brouard
                    685:   *** empty log message ***
                    686: 
1.166     brouard   687:   Revision 1.165  2014/12/16 11:20:36  brouard
                    688:   Summary: After compiling on Visual C
                    689: 
                    690:   * imach.c (Module): Merging 1.61 to 1.162
                    691: 
1.165     brouard   692:   Revision 1.164  2014/12/16 10:52:11  brouard
                    693:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    694: 
                    695:   * imach.c (Module): Merging 1.61 to 1.162
                    696: 
1.164     brouard   697:   Revision 1.163  2014/12/16 10:30:11  brouard
                    698:   * imach.c (Module): Merging 1.61 to 1.162
                    699: 
1.163     brouard   700:   Revision 1.162  2014/09/25 11:43:39  brouard
                    701:   Summary: temporary backup 0.99!
                    702: 
1.162     brouard   703:   Revision 1.1  2014/09/16 11:06:58  brouard
                    704:   Summary: With some code (wrong) for nlopt
                    705: 
                    706:   Author:
                    707: 
                    708:   Revision 1.161  2014/09/15 20:41:41  brouard
                    709:   Summary: Problem with macro SQR on Intel compiler
                    710: 
1.161     brouard   711:   Revision 1.160  2014/09/02 09:24:05  brouard
                    712:   *** empty log message ***
                    713: 
1.160     brouard   714:   Revision 1.159  2014/09/01 10:34:10  brouard
                    715:   Summary: WIN32
                    716:   Author: Brouard
                    717: 
1.159     brouard   718:   Revision 1.158  2014/08/27 17:11:51  brouard
                    719:   *** empty log message ***
                    720: 
1.158     brouard   721:   Revision 1.157  2014/08/27 16:26:55  brouard
                    722:   Summary: Preparing windows Visual studio version
                    723:   Author: Brouard
                    724: 
                    725:   In order to compile on Visual studio, time.h is now correct and time_t
                    726:   and tm struct should be used. difftime should be used but sometimes I
                    727:   just make the differences in raw time format (time(&now).
                    728:   Trying to suppress #ifdef LINUX
                    729:   Add xdg-open for __linux in order to open default browser.
                    730: 
1.157     brouard   731:   Revision 1.156  2014/08/25 20:10:10  brouard
                    732:   *** empty log message ***
                    733: 
1.156     brouard   734:   Revision 1.155  2014/08/25 18:32:34  brouard
                    735:   Summary: New compile, minor changes
                    736:   Author: Brouard
                    737: 
1.155     brouard   738:   Revision 1.154  2014/06/20 17:32:08  brouard
                    739:   Summary: Outputs now all graphs of convergence to period prevalence
                    740: 
1.154     brouard   741:   Revision 1.153  2014/06/20 16:45:46  brouard
                    742:   Summary: If 3 live state, convergence to period prevalence on same graph
                    743:   Author: Brouard
                    744: 
1.153     brouard   745:   Revision 1.152  2014/06/18 17:54:09  brouard
                    746:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    747: 
1.152     brouard   748:   Revision 1.151  2014/06/18 16:43:30  brouard
                    749:   *** empty log message ***
                    750: 
1.151     brouard   751:   Revision 1.150  2014/06/18 16:42:35  brouard
                    752:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    753:   Author: brouard
                    754: 
1.150     brouard   755:   Revision 1.149  2014/06/18 15:51:14  brouard
                    756:   Summary: Some fixes in parameter files errors
                    757:   Author: Nicolas Brouard
                    758: 
1.149     brouard   759:   Revision 1.148  2014/06/17 17:38:48  brouard
                    760:   Summary: Nothing new
                    761:   Author: Brouard
                    762: 
                    763:   Just a new packaging for OS/X version 0.98nS
                    764: 
1.148     brouard   765:   Revision 1.147  2014/06/16 10:33:11  brouard
                    766:   *** empty log message ***
                    767: 
1.147     brouard   768:   Revision 1.146  2014/06/16 10:20:28  brouard
                    769:   Summary: Merge
                    770:   Author: Brouard
                    771: 
                    772:   Merge, before building revised version.
                    773: 
1.146     brouard   774:   Revision 1.145  2014/06/10 21:23:15  brouard
                    775:   Summary: Debugging with valgrind
                    776:   Author: Nicolas Brouard
                    777: 
                    778:   Lot of changes in order to output the results with some covariates
                    779:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    780:   improve the code.
                    781:   No more memory valgrind error but a lot has to be done in order to
                    782:   continue the work of splitting the code into subroutines.
                    783:   Also, decodemodel has been improved. Tricode is still not
                    784:   optimal. nbcode should be improved. Documentation has been added in
                    785:   the source code.
                    786: 
1.144     brouard   787:   Revision 1.143  2014/01/26 09:45:38  brouard
                    788:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    789: 
                    790:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    791:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    792: 
1.143     brouard   793:   Revision 1.142  2014/01/26 03:57:36  brouard
                    794:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    795: 
                    796:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    797: 
1.142     brouard   798:   Revision 1.141  2014/01/26 02:42:01  brouard
                    799:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    800: 
1.141     brouard   801:   Revision 1.140  2011/09/02 10:37:54  brouard
                    802:   Summary: times.h is ok with mingw32 now.
                    803: 
1.140     brouard   804:   Revision 1.139  2010/06/14 07:50:17  brouard
                    805:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    806:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    807: 
1.139     brouard   808:   Revision 1.138  2010/04/30 18:19:40  brouard
                    809:   *** empty log message ***
                    810: 
1.138     brouard   811:   Revision 1.137  2010/04/29 18:11:38  brouard
                    812:   (Module): Checking covariates for more complex models
                    813:   than V1+V2. A lot of change to be done. Unstable.
                    814: 
1.137     brouard   815:   Revision 1.136  2010/04/26 20:30:53  brouard
                    816:   (Module): merging some libgsl code. Fixing computation
                    817:   of likelione (using inter/intrapolation if mle = 0) in order to
                    818:   get same likelihood as if mle=1.
                    819:   Some cleaning of code and comments added.
                    820: 
1.136     brouard   821:   Revision 1.135  2009/10/29 15:33:14  brouard
                    822:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    823: 
1.135     brouard   824:   Revision 1.134  2009/10/29 13:18:53  brouard
                    825:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    826: 
1.134     brouard   827:   Revision 1.133  2009/07/06 10:21:25  brouard
                    828:   just nforces
                    829: 
1.133     brouard   830:   Revision 1.132  2009/07/06 08:22:05  brouard
                    831:   Many tings
                    832: 
1.132     brouard   833:   Revision 1.131  2009/06/20 16:22:47  brouard
                    834:   Some dimensions resccaled
                    835: 
1.131     brouard   836:   Revision 1.130  2009/05/26 06:44:34  brouard
                    837:   (Module): Max Covariate is now set to 20 instead of 8. A
                    838:   lot of cleaning with variables initialized to 0. Trying to make
                    839:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    840: 
1.130     brouard   841:   Revision 1.129  2007/08/31 13:49:27  lievre
                    842:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    843: 
1.129     lievre    844:   Revision 1.128  2006/06/30 13:02:05  brouard
                    845:   (Module): Clarifications on computing e.j
                    846: 
1.128     brouard   847:   Revision 1.127  2006/04/28 18:11:50  brouard
                    848:   (Module): Yes the sum of survivors was wrong since
                    849:   imach-114 because nhstepm was no more computed in the age
                    850:   loop. Now we define nhstepma in the age loop.
                    851:   (Module): In order to speed up (in case of numerous covariates) we
                    852:   compute health expectancies (without variances) in a first step
                    853:   and then all the health expectancies with variances or standard
                    854:   deviation (needs data from the Hessian matrices) which slows the
                    855:   computation.
                    856:   In the future we should be able to stop the program is only health
                    857:   expectancies and graph are needed without standard deviations.
                    858: 
1.127     brouard   859:   Revision 1.126  2006/04/28 17:23:28  brouard
                    860:   (Module): Yes the sum of survivors was wrong since
                    861:   imach-114 because nhstepm was no more computed in the age
                    862:   loop. Now we define nhstepma in the age loop.
                    863:   Version 0.98h
                    864: 
1.126     brouard   865:   Revision 1.125  2006/04/04 15:20:31  lievre
                    866:   Errors in calculation of health expectancies. Age was not initialized.
                    867:   Forecasting file added.
                    868: 
                    869:   Revision 1.124  2006/03/22 17:13:53  lievre
                    870:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    871:   The log-likelihood is printed in the log file
                    872: 
                    873:   Revision 1.123  2006/03/20 10:52:43  brouard
                    874:   * imach.c (Module): <title> changed, corresponds to .htm file
                    875:   name. <head> headers where missing.
                    876: 
                    877:   * imach.c (Module): Weights can have a decimal point as for
                    878:   English (a comma might work with a correct LC_NUMERIC environment,
                    879:   otherwise the weight is truncated).
                    880:   Modification of warning when the covariates values are not 0 or
                    881:   1.
                    882:   Version 0.98g
                    883: 
                    884:   Revision 1.122  2006/03/20 09:45:41  brouard
                    885:   (Module): Weights can have a decimal point as for
                    886:   English (a comma might work with a correct LC_NUMERIC environment,
                    887:   otherwise the weight is truncated).
                    888:   Modification of warning when the covariates values are not 0 or
                    889:   1.
                    890:   Version 0.98g
                    891: 
                    892:   Revision 1.121  2006/03/16 17:45:01  lievre
                    893:   * imach.c (Module): Comments concerning covariates added
                    894: 
                    895:   * imach.c (Module): refinements in the computation of lli if
                    896:   status=-2 in order to have more reliable computation if stepm is
                    897:   not 1 month. Version 0.98f
                    898: 
                    899:   Revision 1.120  2006/03/16 15:10:38  lievre
                    900:   (Module): refinements in the computation of lli if
                    901:   status=-2 in order to have more reliable computation if stepm is
                    902:   not 1 month. Version 0.98f
                    903: 
                    904:   Revision 1.119  2006/03/15 17:42:26  brouard
                    905:   (Module): Bug if status = -2, the loglikelihood was
                    906:   computed as likelihood omitting the logarithm. Version O.98e
                    907: 
                    908:   Revision 1.118  2006/03/14 18:20:07  brouard
                    909:   (Module): varevsij Comments added explaining the second
                    910:   table of variances if popbased=1 .
                    911:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    912:   (Module): Function pstamp added
                    913:   (Module): Version 0.98d
                    914: 
                    915:   Revision 1.117  2006/03/14 17:16:22  brouard
                    916:   (Module): varevsij Comments added explaining the second
                    917:   table of variances if popbased=1 .
                    918:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    919:   (Module): Function pstamp added
                    920:   (Module): Version 0.98d
                    921: 
                    922:   Revision 1.116  2006/03/06 10:29:27  brouard
                    923:   (Module): Variance-covariance wrong links and
                    924:   varian-covariance of ej. is needed (Saito).
                    925: 
                    926:   Revision 1.115  2006/02/27 12:17:45  brouard
                    927:   (Module): One freematrix added in mlikeli! 0.98c
                    928: 
                    929:   Revision 1.114  2006/02/26 12:57:58  brouard
                    930:   (Module): Some improvements in processing parameter
                    931:   filename with strsep.
                    932: 
                    933:   Revision 1.113  2006/02/24 14:20:24  brouard
                    934:   (Module): Memory leaks checks with valgrind and:
                    935:   datafile was not closed, some imatrix were not freed and on matrix
                    936:   allocation too.
                    937: 
                    938:   Revision 1.112  2006/01/30 09:55:26  brouard
                    939:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    940: 
                    941:   Revision 1.111  2006/01/25 20:38:18  brouard
                    942:   (Module): Lots of cleaning and bugs added (Gompertz)
                    943:   (Module): Comments can be added in data file. Missing date values
                    944:   can be a simple dot '.'.
                    945: 
                    946:   Revision 1.110  2006/01/25 00:51:50  brouard
                    947:   (Module): Lots of cleaning and bugs added (Gompertz)
                    948: 
                    949:   Revision 1.109  2006/01/24 19:37:15  brouard
                    950:   (Module): Comments (lines starting with a #) are allowed in data.
                    951: 
                    952:   Revision 1.108  2006/01/19 18:05:42  lievre
                    953:   Gnuplot problem appeared...
                    954:   To be fixed
                    955: 
                    956:   Revision 1.107  2006/01/19 16:20:37  brouard
                    957:   Test existence of gnuplot in imach path
                    958: 
                    959:   Revision 1.106  2006/01/19 13:24:36  brouard
                    960:   Some cleaning and links added in html output
                    961: 
                    962:   Revision 1.105  2006/01/05 20:23:19  lievre
                    963:   *** empty log message ***
                    964: 
                    965:   Revision 1.104  2005/09/30 16:11:43  lievre
                    966:   (Module): sump fixed, loop imx fixed, and simplifications.
                    967:   (Module): If the status is missing at the last wave but we know
                    968:   that the person is alive, then we can code his/her status as -2
                    969:   (instead of missing=-1 in earlier versions) and his/her
                    970:   contributions to the likelihood is 1 - Prob of dying from last
                    971:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    972:   the healthy state at last known wave). Version is 0.98
                    973: 
                    974:   Revision 1.103  2005/09/30 15:54:49  lievre
                    975:   (Module): sump fixed, loop imx fixed, and simplifications.
                    976: 
                    977:   Revision 1.102  2004/09/15 17:31:30  brouard
                    978:   Add the possibility to read data file including tab characters.
                    979: 
                    980:   Revision 1.101  2004/09/15 10:38:38  brouard
                    981:   Fix on curr_time
                    982: 
                    983:   Revision 1.100  2004/07/12 18:29:06  brouard
                    984:   Add version for Mac OS X. Just define UNIX in Makefile
                    985: 
                    986:   Revision 1.99  2004/06/05 08:57:40  brouard
                    987:   *** empty log message ***
                    988: 
                    989:   Revision 1.98  2004/05/16 15:05:56  brouard
                    990:   New version 0.97 . First attempt to estimate force of mortality
                    991:   directly from the data i.e. without the need of knowing the health
                    992:   state at each age, but using a Gompertz model: log u =a + b*age .
                    993:   This is the basic analysis of mortality and should be done before any
                    994:   other analysis, in order to test if the mortality estimated from the
                    995:   cross-longitudinal survey is different from the mortality estimated
                    996:   from other sources like vital statistic data.
                    997: 
                    998:   The same imach parameter file can be used but the option for mle should be -3.
                    999: 
1.324     brouard  1000:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1001:   former routines in order to include the new code within the former code.
                   1002: 
                   1003:   The output is very simple: only an estimate of the intercept and of
                   1004:   the slope with 95% confident intervals.
                   1005: 
                   1006:   Current limitations:
                   1007:   A) Even if you enter covariates, i.e. with the
                   1008:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1009:   B) There is no computation of Life Expectancy nor Life Table.
                   1010: 
                   1011:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1012:   Version 0.96d. Population forecasting command line is (temporarily)
                   1013:   suppressed.
                   1014: 
                   1015:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1016:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1017:   rewritten within the same printf. Workaround: many printfs.
                   1018: 
                   1019:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1020:   * imach.c (Repository):
                   1021:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1022:   matrix (cov(a12,c31) instead of numbers.
                   1023: 
                   1024:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1025:   Just cleaning
                   1026: 
                   1027:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1028:   (Module): On windows (cygwin) function asctime_r doesn't
                   1029:   exist so I changed back to asctime which exists.
                   1030:   (Module): Version 0.96b
                   1031: 
                   1032:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1033:   (Module): On windows (cygwin) function asctime_r doesn't
                   1034:   exist so I changed back to asctime which exists.
                   1035: 
                   1036:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1037:   * imach.c (Repository): Duplicated warning errors corrected.
                   1038:   (Repository): Elapsed time after each iteration is now output. It
                   1039:   helps to forecast when convergence will be reached. Elapsed time
                   1040:   is stamped in powell.  We created a new html file for the graphs
                   1041:   concerning matrix of covariance. It has extension -cov.htm.
                   1042: 
                   1043:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1044:   (Module): Some bugs corrected for windows. Also, when
                   1045:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1046:   of the covariance matrix to be input.
                   1047: 
                   1048:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1049:   (Module): Some bugs corrected for windows. Also, when
                   1050:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1051:   of the covariance matrix to be input.
                   1052: 
                   1053:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1054:   * 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.
                   1055: 
                   1056:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1057:   Version 0.96
                   1058: 
                   1059:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1060:   (Module): Change position of html and gnuplot routines and added
                   1061:   routine fileappend.
                   1062: 
                   1063:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1064:   * imach.c (Repository): Check when date of death was earlier that
                   1065:   current date of interview. It may happen when the death was just
                   1066:   prior to the death. In this case, dh was negative and likelihood
                   1067:   was wrong (infinity). We still send an "Error" but patch by
                   1068:   assuming that the date of death was just one stepm after the
                   1069:   interview.
                   1070:   (Repository): Because some people have very long ID (first column)
                   1071:   we changed int to long in num[] and we added a new lvector for
                   1072:   memory allocation. But we also truncated to 8 characters (left
                   1073:   truncation)
                   1074:   (Repository): No more line truncation errors.
                   1075: 
                   1076:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1077:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1078:   place. It differs from routine "prevalence" which may be called
                   1079:   many times. Probs is memory consuming and must be used with
                   1080:   parcimony.
                   1081:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1082: 
                   1083:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1084:   *** empty log message ***
                   1085: 
                   1086:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1087:   Add log in  imach.c and  fullversion number is now printed.
                   1088: 
                   1089: */
                   1090: /*
                   1091:    Interpolated Markov Chain
                   1092: 
                   1093:   Short summary of the programme:
                   1094:   
1.227     brouard  1095:   This program computes Healthy Life Expectancies or State-specific
                   1096:   (if states aren't health statuses) Expectancies from
                   1097:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1098: 
                   1099:   -1- a first survey ("cross") where individuals from different ages
                   1100:   are interviewed on their health status or degree of disability (in
                   1101:   the case of a health survey which is our main interest)
                   1102: 
                   1103:   -2- at least a second wave of interviews ("longitudinal") which
                   1104:   measure each change (if any) in individual health status.  Health
                   1105:   expectancies are computed from the time spent in each health state
                   1106:   according to a model. More health states you consider, more time is
                   1107:   necessary to reach the Maximum Likelihood of the parameters involved
                   1108:   in the model.  The simplest model is the multinomial logistic model
                   1109:   where pij is the probability to be observed in state j at the second
                   1110:   wave conditional to be observed in state i at the first
                   1111:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1112:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1113:   have a more complex model than "constant and age", you should modify
                   1114:   the program where the markup *Covariates have to be included here
                   1115:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1116:   convergence.
                   1117: 
                   1118:   The advantage of this computer programme, compared to a simple
                   1119:   multinomial logistic model, is clear when the delay between waves is not
                   1120:   identical for each individual. Also, if a individual missed an
                   1121:   intermediate interview, the information is lost, but taken into
                   1122:   account using an interpolation or extrapolation.  
                   1123: 
                   1124:   hPijx is the probability to be observed in state i at age x+h
                   1125:   conditional to the observed state i at age x. The delay 'h' can be
                   1126:   split into an exact number (nh*stepm) of unobserved intermediate
                   1127:   states. This elementary transition (by month, quarter,
                   1128:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1129:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1130:   and the contribution of each individual to the likelihood is simply
                   1131:   hPijx.
                   1132: 
                   1133:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1134:   of the life expectancies. It also computes the period (stable) prevalence.
                   1135: 
                   1136: Back prevalence and projections:
1.227     brouard  1137: 
                   1138:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1139:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1140:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1141:    mobilavproj)
                   1142: 
                   1143:     Computes the back prevalence limit for any combination of
                   1144:     covariate values k at any age between ageminpar and agemaxpar and
                   1145:     returns it in **bprlim. In the loops,
                   1146: 
                   1147:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1148:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1149: 
                   1150:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1151:    Computes for any combination of covariates k and any age between bage and fage 
                   1152:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1153:                        oldm=oldms;savm=savms;
1.227     brouard  1154: 
1.267     brouard  1155:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1156:      Computes the transition matrix starting at age 'age' over
                   1157:      'nhstepm*hstepm*stepm' months (i.e. until
                   1158:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1159:      nhstepm*hstepm matrices. 
                   1160: 
                   1161:      Returns p3mat[i][j][h] after calling
                   1162:      p3mat[i][j][h]=matprod2(newm,
                   1163:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1164:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1165:      oldm);
1.226     brouard  1166: 
                   1167: Important routines
                   1168: 
                   1169: - func (or funcone), computes logit (pij) distinguishing
                   1170:   o fixed variables (single or product dummies or quantitative);
                   1171:   o varying variables by:
                   1172:    (1) wave (single, product dummies, quantitative), 
                   1173:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1174:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1175:        % varying dummy (not done) or quantitative (not done);
                   1176: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1177:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1178: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1179:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1180:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1181: 
1.226     brouard  1182: 
                   1183:   
1.324     brouard  1184:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1185:            Institut national d'études démographiques, Paris.
1.126     brouard  1186:   This software have been partly granted by Euro-REVES, a concerted action
                   1187:   from the European Union.
                   1188:   It is copyrighted identically to a GNU software product, ie programme and
                   1189:   software can be distributed freely for non commercial use. Latest version
                   1190:   can be accessed at http://euroreves.ined.fr/imach .
                   1191: 
                   1192:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1193:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1194:   
                   1195:   **********************************************************************/
                   1196: /*
                   1197:   main
                   1198:   read parameterfile
                   1199:   read datafile
                   1200:   concatwav
                   1201:   freqsummary
                   1202:   if (mle >= 1)
                   1203:     mlikeli
                   1204:   print results files
                   1205:   if mle==1 
                   1206:      computes hessian
                   1207:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1208:       begin-prev-date,...
                   1209:   open gnuplot file
                   1210:   open html file
1.145     brouard  1211:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1212:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1213:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1214:     freexexit2 possible for memory heap.
                   1215: 
                   1216:   h Pij x                         | pij_nom  ficrestpij
                   1217:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1218:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1219:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1220: 
                   1221:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1222:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1223:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1224:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1225:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1226: 
1.126     brouard  1227:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1228:   health expectancies
                   1229:   Variance-covariance of DFLE
                   1230:   prevalence()
                   1231:    movingaverage()
                   1232:   varevsij() 
                   1233:   if popbased==1 varevsij(,popbased)
                   1234:   total life expectancies
                   1235:   Variance of period (stable) prevalence
                   1236:  end
                   1237: */
                   1238: 
1.187     brouard  1239: /* #define DEBUG */
                   1240: /* #define DEBUGBRENT */
1.203     brouard  1241: /* #define DEBUGLINMIN */
                   1242: /* #define DEBUGHESS */
                   1243: #define DEBUGHESSIJ
1.224     brouard  1244: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1245: #define POWELL /* Instead of NLOPT */
1.224     brouard  1246: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1247: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1248: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1249: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1250: 
                   1251: #include <math.h>
                   1252: #include <stdio.h>
                   1253: #include <stdlib.h>
                   1254: #include <string.h>
1.226     brouard  1255: #include <ctype.h>
1.159     brouard  1256: 
                   1257: #ifdef _WIN32
                   1258: #include <io.h>
1.172     brouard  1259: #include <windows.h>
                   1260: #include <tchar.h>
1.159     brouard  1261: #else
1.126     brouard  1262: #include <unistd.h>
1.159     brouard  1263: #endif
1.126     brouard  1264: 
                   1265: #include <limits.h>
                   1266: #include <sys/types.h>
1.171     brouard  1267: 
                   1268: #if defined(__GNUC__)
                   1269: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1270: #endif
                   1271: 
1.126     brouard  1272: #include <sys/stat.h>
                   1273: #include <errno.h>
1.159     brouard  1274: /* extern int errno; */
1.126     brouard  1275: 
1.157     brouard  1276: /* #ifdef LINUX */
                   1277: /* #include <time.h> */
                   1278: /* #include "timeval.h" */
                   1279: /* #else */
                   1280: /* #include <sys/time.h> */
                   1281: /* #endif */
                   1282: 
1.126     brouard  1283: #include <time.h>
                   1284: 
1.136     brouard  1285: #ifdef GSL
                   1286: #include <gsl/gsl_errno.h>
                   1287: #include <gsl/gsl_multimin.h>
                   1288: #endif
                   1289: 
1.167     brouard  1290: 
1.162     brouard  1291: #ifdef NLOPT
                   1292: #include <nlopt.h>
                   1293: typedef struct {
                   1294:   double (* function)(double [] );
                   1295: } myfunc_data ;
                   1296: #endif
                   1297: 
1.126     brouard  1298: /* #include <libintl.h> */
                   1299: /* #define _(String) gettext (String) */
                   1300: 
1.251     brouard  1301: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1302: 
                   1303: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1304: #define GNUPLOTVERSION 5.1
                   1305: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1306: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1307: #define FILENAMELENGTH 256
1.126     brouard  1308: 
                   1309: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1310: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1311: 
1.144     brouard  1312: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1313: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1314: 
                   1315: #define NINTERVMAX 8
1.144     brouard  1316: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1317: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1318: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1319: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1320: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1321: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1322: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1323: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1324: /* #define AGESUP 130 */
1.288     brouard  1325: /* #define AGESUP 150 */
                   1326: #define AGESUP 200
1.268     brouard  1327: #define AGEINF 0
1.218     brouard  1328: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1329: #define AGEBASE 40
1.194     brouard  1330: #define AGEOVERFLOW 1.e20
1.164     brouard  1331: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1332: #ifdef _WIN32
                   1333: #define DIRSEPARATOR '\\'
                   1334: #define CHARSEPARATOR "\\"
                   1335: #define ODIRSEPARATOR '/'
                   1336: #else
1.126     brouard  1337: #define DIRSEPARATOR '/'
                   1338: #define CHARSEPARATOR "/"
                   1339: #define ODIRSEPARATOR '\\'
                   1340: #endif
                   1341: 
1.344   ! brouard  1342: /* $Id: imach.c,v 1.343 2022/09/14 14:22:16 brouard Exp $ */
1.126     brouard  1343: /* $State: Exp $ */
1.196     brouard  1344: #include "version.h"
                   1345: char version[]=__IMACH_VERSION__;
1.337     brouard  1346: 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.344   ! brouard  1347: char fullversion[]="$Revision: 1.343 $ $Date: 2022/09/14 14:22:16 $"; 
1.126     brouard  1348: char strstart[80];
                   1349: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1350: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1351: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1352: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1353: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1354: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1355: 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  1356: 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  1357: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1358: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1359: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1360: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1361: 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  1362: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1363: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1364: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1365: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1366: int nsd=0; /**< Total number of single dummy variables (output) */
                   1367: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1368: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1369: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1370: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1371: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1372: int cptcov=0; /* Working variable */
1.334     brouard  1373: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1374: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1375: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1376: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1377: int nlstate=2; /* Number of live states */
                   1378: int ndeath=1; /* Number of dead states */
1.130     brouard  1379: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1380: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1381: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1382: int popbased=0;
                   1383: 
                   1384: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1385: int maxwav=0; /* Maxim number of waves */
                   1386: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1387: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1388: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1389:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1390: int mle=1, weightopt=0;
1.126     brouard  1391: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1392: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1393: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1394:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1395: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1396: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1397: 
1.130     brouard  1398: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1399: double **matprod2(); /* test */
1.126     brouard  1400: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1401: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1402: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1403: 
1.136     brouard  1404: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1405: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1406: FILE *ficlog, *ficrespow;
1.130     brouard  1407: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1408: double fretone; /* Only one call to likelihood */
1.130     brouard  1409: long ipmx=0; /* Number of contributions */
1.126     brouard  1410: double sw; /* Sum of weights */
                   1411: char filerespow[FILENAMELENGTH];
                   1412: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1413: FILE *ficresilk;
                   1414: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1415: FILE *ficresprobmorprev;
                   1416: FILE *fichtm, *fichtmcov; /* Html File */
                   1417: FILE *ficreseij;
                   1418: char filerese[FILENAMELENGTH];
                   1419: FILE *ficresstdeij;
                   1420: char fileresstde[FILENAMELENGTH];
                   1421: FILE *ficrescveij;
                   1422: char filerescve[FILENAMELENGTH];
                   1423: FILE  *ficresvij;
                   1424: char fileresv[FILENAMELENGTH];
1.269     brouard  1425: 
1.126     brouard  1426: char title[MAXLINE];
1.234     brouard  1427: char model[MAXLINE]; /**< The model line */
1.217     brouard  1428: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1429: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1430: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1431: char command[FILENAMELENGTH];
                   1432: int  outcmd=0;
                   1433: 
1.217     brouard  1434: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1435: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1436: char filelog[FILENAMELENGTH]; /* Log file */
                   1437: char filerest[FILENAMELENGTH];
                   1438: char fileregp[FILENAMELENGTH];
                   1439: char popfile[FILENAMELENGTH];
                   1440: 
                   1441: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1442: 
1.157     brouard  1443: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1444: /* struct timezone tzp; */
                   1445: /* extern int gettimeofday(); */
                   1446: struct tm tml, *gmtime(), *localtime();
                   1447: 
                   1448: extern time_t time();
                   1449: 
                   1450: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1451: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1452: struct tm tm;
                   1453: 
1.126     brouard  1454: char strcurr[80], strfor[80];
                   1455: 
                   1456: char *endptr;
                   1457: long lval;
                   1458: double dval;
                   1459: 
                   1460: #define NR_END 1
                   1461: #define FREE_ARG char*
                   1462: #define FTOL 1.0e-10
                   1463: 
                   1464: #define NRANSI 
1.240     brouard  1465: #define ITMAX 200
                   1466: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1467: 
                   1468: #define TOL 2.0e-4 
                   1469: 
                   1470: #define CGOLD 0.3819660 
                   1471: #define ZEPS 1.0e-10 
                   1472: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1473: 
                   1474: #define GOLD 1.618034 
                   1475: #define GLIMIT 100.0 
                   1476: #define TINY 1.0e-20 
                   1477: 
                   1478: static double maxarg1,maxarg2;
                   1479: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1480: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1481:   
                   1482: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1483: #define rint(a) floor(a+0.5)
1.166     brouard  1484: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1485: #define mytinydouble 1.0e-16
1.166     brouard  1486: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1487: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1488: /* static double dsqrarg; */
                   1489: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1490: static double sqrarg;
                   1491: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1492: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1493: int agegomp= AGEGOMP;
                   1494: 
                   1495: int imx; 
                   1496: int stepm=1;
                   1497: /* Stepm, step in month: minimum step interpolation*/
                   1498: 
                   1499: int estepm;
                   1500: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1501: 
                   1502: int m,nb;
                   1503: long *num;
1.197     brouard  1504: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1505: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1506:                   covariate for which somebody answered excluding 
                   1507:                   undefined. Usually 2: 0 and 1. */
                   1508: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1509:                             covariate for which somebody answered including 
                   1510:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1511: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1512: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1513: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1514: 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  1515: double *ageexmed,*agecens;
                   1516: double dateintmean=0;
1.296     brouard  1517:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1518:   double anprojf, mprojf, jprojf;
1.126     brouard  1519: 
1.296     brouard  1520:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1521:   double anbackf, mbackf, jbackf;
                   1522:   double jintmean,mintmean,aintmean;  
1.126     brouard  1523: double *weight;
                   1524: int **s; /* Status */
1.141     brouard  1525: double *agedc;
1.145     brouard  1526: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1527:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1528:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1529: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1530: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1531: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1532: double  idx; 
                   1533: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1534: /* Some documentation */
                   1535:       /*   Design original data
                   1536:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1537:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1538:        *                                                             ntv=3     nqtv=1
1.330     brouard  1539:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1540:        * For time varying covariate, quanti or dummies
                   1541:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1542:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1543:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1544:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1545:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1546:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1547:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1548:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1549:        */
                   1550: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1551: /* 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
                   1552:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1553:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1554: */
1.343     brouard  1555: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1 */
                   1556: /*    kmodel  1  2   3   4     5    6    7     8    9 */
1.319     brouard  1557: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1558:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1559:                                                          /* product */
                   1560: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1561:                                                          /*(single or product without age), 2 dummy*/
                   1562:                                                          /* with age product, 3 quant with age product*/
                   1563: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1564: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1565: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1566: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1567: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1568: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1569: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1570: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1571: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1572: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1573: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1574: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1575: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1576: /* 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  1577: /* 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  1578: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1579: /* Type                    */
                   1580: /* V         1  2  3  4  5 */
                   1581: /*           F  F  V  V  V */
                   1582: /*           D  Q  D  D  Q */
                   1583: /*                         */
                   1584: int *TvarsD;
1.330     brouard  1585: int *TnsdVar;
1.234     brouard  1586: int *TvarsDind;
                   1587: int *TvarsQ;
                   1588: int *TvarsQind;
                   1589: 
1.318     brouard  1590: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1591: int nresult=0;
1.258     brouard  1592: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1593: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1594: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1595: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1596: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1597: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1598: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1599: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1600: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1601: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1602: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1603: 
                   1604: /* 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
                   1605:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1606:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1607: */
1.234     brouard  1608: /* 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  1609: 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 */
                   1610: 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 */
                   1611: 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 */
                   1612: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1613: 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 */
                   1614: 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  1615: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1616: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1617: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1618: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1619: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1620: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1621: 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 */
                   1622: 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  1623: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1624: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1625:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1626:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1627:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1628:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1629:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1630: int *Tvarsel; /**< Selected covariates for output */
                   1631: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1632: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1633: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1634: 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  1635: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1636: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1637: int *Tage;
1.227     brouard  1638: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1639: 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  1640: 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*/ 
                   1641: 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  1642: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1643: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1644: int **Tvard;
1.330     brouard  1645: int **Tvardk;
1.227     brouard  1646: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1647: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1648: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1649:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1650:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1651: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1652: double *lsurv, *lpop, *tpop;
                   1653: 
1.231     brouard  1654: #define FD 1; /* Fixed dummy covariate */
                   1655: #define FQ 2; /* Fixed quantitative covariate */
                   1656: #define FP 3; /* Fixed product covariate */
                   1657: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1658: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1659: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1660: #define VD 10; /* Varying dummy covariate */
                   1661: #define VQ 11; /* Varying quantitative covariate */
                   1662: #define VP 12; /* Varying product covariate */
                   1663: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1664: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1665: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1666: #define APFD 16; /* Age product * fixed dummy covariate */
                   1667: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1668: #define APVD 18; /* Age product * varying dummy covariate */
                   1669: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1670: 
                   1671: #define FTYPE 1; /* Fixed covariate */
                   1672: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1673: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1674: 
                   1675: struct kmodel{
                   1676:        int maintype; /* main type */
                   1677:        int subtype; /* subtype */
                   1678: };
                   1679: struct kmodel modell[NCOVMAX];
                   1680: 
1.143     brouard  1681: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1682: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1683: 
                   1684: /**************** split *************************/
                   1685: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1686: {
                   1687:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1688:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1689:   */ 
                   1690:   char *ss;                            /* pointer */
1.186     brouard  1691:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1692: 
                   1693:   l1 = strlen(path );                  /* length of path */
                   1694:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1695:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1696:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1697:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1698:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1699:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1700:     /* get current working directory */
                   1701:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1702: #ifdef WIN32
                   1703:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1704: #else
                   1705:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1706: #endif
1.126     brouard  1707:       return( GLOCK_ERROR_GETCWD );
                   1708:     }
                   1709:     /* got dirc from getcwd*/
                   1710:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1711:   } else {                             /* strip directory from path */
1.126     brouard  1712:     ss++;                              /* after this, the filename */
                   1713:     l2 = strlen( ss );                 /* length of filename */
                   1714:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1715:     strcpy( name, ss );                /* save file name */
                   1716:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1717:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1718:     printf(" DIRC2 = %s \n",dirc);
                   1719:   }
                   1720:   /* We add a separator at the end of dirc if not exists */
                   1721:   l1 = strlen( dirc );                 /* length of directory */
                   1722:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1723:     dirc[l1] =  DIRSEPARATOR;
                   1724:     dirc[l1+1] = 0; 
                   1725:     printf(" DIRC3 = %s \n",dirc);
                   1726:   }
                   1727:   ss = strrchr( name, '.' );           /* find last / */
                   1728:   if (ss >0){
                   1729:     ss++;
                   1730:     strcpy(ext,ss);                    /* save extension */
                   1731:     l1= strlen( name);
                   1732:     l2= strlen(ss)+1;
                   1733:     strncpy( finame, name, l1-l2);
                   1734:     finame[l1-l2]= 0;
                   1735:   }
                   1736: 
                   1737:   return( 0 );                         /* we're done */
                   1738: }
                   1739: 
                   1740: 
                   1741: /******************************************/
                   1742: 
                   1743: void replace_back_to_slash(char *s, char*t)
                   1744: {
                   1745:   int i;
                   1746:   int lg=0;
                   1747:   i=0;
                   1748:   lg=strlen(t);
                   1749:   for(i=0; i<= lg; i++) {
                   1750:     (s[i] = t[i]);
                   1751:     if (t[i]== '\\') s[i]='/';
                   1752:   }
                   1753: }
                   1754: 
1.132     brouard  1755: char *trimbb(char *out, char *in)
1.137     brouard  1756: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1757:   char *s;
                   1758:   s=out;
                   1759:   while (*in != '\0'){
1.137     brouard  1760:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1761:       in++;
                   1762:     }
                   1763:     *out++ = *in++;
                   1764:   }
                   1765:   *out='\0';
                   1766:   return s;
                   1767: }
                   1768: 
1.187     brouard  1769: /* char *substrchaine(char *out, char *in, char *chain) */
                   1770: /* { */
                   1771: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1772: /*   char *s, *t; */
                   1773: /*   t=in;s=out; */
                   1774: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1775: /*     *out++ = *in++; */
                   1776: /*   } */
                   1777: 
                   1778: /*   /\* *in matches *chain *\/ */
                   1779: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1780: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1781: /*   } */
                   1782: /*   in--; chain--; */
                   1783: /*   while ( (*in != '\0')){ */
                   1784: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1785: /*     *out++ = *in++; */
                   1786: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1787: /*   } */
                   1788: /*   *out='\0'; */
                   1789: /*   out=s; */
                   1790: /*   return out; */
                   1791: /* } */
                   1792: char *substrchaine(char *out, char *in, char *chain)
                   1793: {
                   1794:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1795:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1796: 
                   1797:   char *strloc;
                   1798: 
                   1799:   strcpy (out, in); 
                   1800:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1801:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1802:   if(strloc != NULL){ 
                   1803:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1804:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1805:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1806:   }
                   1807:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1808:   return out;
                   1809: }
                   1810: 
                   1811: 
1.145     brouard  1812: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1813: {
1.187     brouard  1814:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1815:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1816:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1817:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1818:   */
1.160     brouard  1819:   char *s, *t;
1.145     brouard  1820:   t=in;s=in;
                   1821:   while ((*in != occ) && (*in != '\0')){
                   1822:     *alocc++ = *in++;
                   1823:   }
                   1824:   if( *in == occ){
                   1825:     *(alocc)='\0';
                   1826:     s=++in;
                   1827:   }
                   1828:  
                   1829:   if (s == t) {/* occ not found */
                   1830:     *(alocc-(in-s))='\0';
                   1831:     in=s;
                   1832:   }
                   1833:   while ( *in != '\0'){
                   1834:     *blocc++ = *in++;
                   1835:   }
                   1836: 
                   1837:   *blocc='\0';
                   1838:   return t;
                   1839: }
1.137     brouard  1840: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1841: {
1.187     brouard  1842:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1843:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1844:      gives blocc="abcdef2ghi" and alocc="j".
                   1845:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1846:   */
                   1847:   char *s, *t;
                   1848:   t=in;s=in;
                   1849:   while (*in != '\0'){
                   1850:     while( *in == occ){
                   1851:       *blocc++ = *in++;
                   1852:       s=in;
                   1853:     }
                   1854:     *blocc++ = *in++;
                   1855:   }
                   1856:   if (s == t) /* occ not found */
                   1857:     *(blocc-(in-s))='\0';
                   1858:   else
                   1859:     *(blocc-(in-s)-1)='\0';
                   1860:   in=s;
                   1861:   while ( *in != '\0'){
                   1862:     *alocc++ = *in++;
                   1863:   }
                   1864: 
                   1865:   *alocc='\0';
                   1866:   return s;
                   1867: }
                   1868: 
1.126     brouard  1869: int nbocc(char *s, char occ)
                   1870: {
                   1871:   int i,j=0;
                   1872:   int lg=20;
                   1873:   i=0;
                   1874:   lg=strlen(s);
                   1875:   for(i=0; i<= lg; i++) {
1.234     brouard  1876:     if  (s[i] == occ ) j++;
1.126     brouard  1877:   }
                   1878:   return j;
                   1879: }
                   1880: 
1.137     brouard  1881: /* void cutv(char *u,char *v, char*t, char occ) */
                   1882: /* { */
                   1883: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1884: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1885: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1886: /*   int i,lg,j,p=0; */
                   1887: /*   i=0; */
                   1888: /*   lg=strlen(t); */
                   1889: /*   for(j=0; j<=lg-1; j++) { */
                   1890: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1891: /*   } */
1.126     brouard  1892: 
1.137     brouard  1893: /*   for(j=0; j<p; j++) { */
                   1894: /*     (u[j] = t[j]); */
                   1895: /*   } */
                   1896: /*      u[p]='\0'; */
1.126     brouard  1897: 
1.137     brouard  1898: /*    for(j=0; j<= lg; j++) { */
                   1899: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1900: /*   } */
                   1901: /* } */
1.126     brouard  1902: 
1.160     brouard  1903: #ifdef _WIN32
                   1904: char * strsep(char **pp, const char *delim)
                   1905: {
                   1906:   char *p, *q;
                   1907:          
                   1908:   if ((p = *pp) == NULL)
                   1909:     return 0;
                   1910:   if ((q = strpbrk (p, delim)) != NULL)
                   1911:   {
                   1912:     *pp = q + 1;
                   1913:     *q = '\0';
                   1914:   }
                   1915:   else
                   1916:     *pp = 0;
                   1917:   return p;
                   1918: }
                   1919: #endif
                   1920: 
1.126     brouard  1921: /********************** nrerror ********************/
                   1922: 
                   1923: void nrerror(char error_text[])
                   1924: {
                   1925:   fprintf(stderr,"ERREUR ...\n");
                   1926:   fprintf(stderr,"%s\n",error_text);
                   1927:   exit(EXIT_FAILURE);
                   1928: }
                   1929: /*********************** vector *******************/
                   1930: double *vector(int nl, int nh)
                   1931: {
                   1932:   double *v;
                   1933:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1934:   if (!v) nrerror("allocation failure in vector");
                   1935:   return v-nl+NR_END;
                   1936: }
                   1937: 
                   1938: /************************ free vector ******************/
                   1939: void free_vector(double*v, int nl, int nh)
                   1940: {
                   1941:   free((FREE_ARG)(v+nl-NR_END));
                   1942: }
                   1943: 
                   1944: /************************ivector *******************************/
                   1945: int *ivector(long nl,long nh)
                   1946: {
                   1947:   int *v;
                   1948:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1949:   if (!v) nrerror("allocation failure in ivector");
                   1950:   return v-nl+NR_END;
                   1951: }
                   1952: 
                   1953: /******************free ivector **************************/
                   1954: void free_ivector(int *v, long nl, long nh)
                   1955: {
                   1956:   free((FREE_ARG)(v+nl-NR_END));
                   1957: }
                   1958: 
                   1959: /************************lvector *******************************/
                   1960: long *lvector(long nl,long nh)
                   1961: {
                   1962:   long *v;
                   1963:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1964:   if (!v) nrerror("allocation failure in ivector");
                   1965:   return v-nl+NR_END;
                   1966: }
                   1967: 
                   1968: /******************free lvector **************************/
                   1969: void free_lvector(long *v, long nl, long nh)
                   1970: {
                   1971:   free((FREE_ARG)(v+nl-NR_END));
                   1972: }
                   1973: 
                   1974: /******************* imatrix *******************************/
                   1975: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1976:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1977: { 
                   1978:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1979:   int **m; 
                   1980:   
                   1981:   /* allocate pointers to rows */ 
                   1982:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1983:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1984:   m += NR_END; 
                   1985:   m -= nrl; 
                   1986:   
                   1987:   
                   1988:   /* allocate rows and set pointers to them */ 
                   1989:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1990:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1991:   m[nrl] += NR_END; 
                   1992:   m[nrl] -= ncl; 
                   1993:   
                   1994:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1995:   
                   1996:   /* return pointer to array of pointers to rows */ 
                   1997:   return m; 
                   1998: } 
                   1999: 
                   2000: /****************** free_imatrix *************************/
                   2001: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2002:       int **m;
                   2003:       long nch,ncl,nrh,nrl; 
                   2004:      /* free an int matrix allocated by imatrix() */ 
                   2005: { 
                   2006:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2007:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2008: } 
                   2009: 
                   2010: /******************* matrix *******************************/
                   2011: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2012: {
                   2013:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2014:   double **m;
                   2015: 
                   2016:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2017:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2018:   m += NR_END;
                   2019:   m -= nrl;
                   2020: 
                   2021:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2022:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2023:   m[nrl] += NR_END;
                   2024:   m[nrl] -= ncl;
                   2025: 
                   2026:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2027:   return m;
1.145     brouard  2028:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2029: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2030: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2031:    */
                   2032: }
                   2033: 
                   2034: /*************************free matrix ************************/
                   2035: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2036: {
                   2037:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2038:   free((FREE_ARG)(m+nrl-NR_END));
                   2039: }
                   2040: 
                   2041: /******************* ma3x *******************************/
                   2042: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2043: {
                   2044:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2045:   double ***m;
                   2046: 
                   2047:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2048:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2049:   m += NR_END;
                   2050:   m -= nrl;
                   2051: 
                   2052:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2053:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2054:   m[nrl] += NR_END;
                   2055:   m[nrl] -= ncl;
                   2056: 
                   2057:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2058: 
                   2059:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2060:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2061:   m[nrl][ncl] += NR_END;
                   2062:   m[nrl][ncl] -= nll;
                   2063:   for (j=ncl+1; j<=nch; j++) 
                   2064:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2065:   
                   2066:   for (i=nrl+1; i<=nrh; i++) {
                   2067:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2068:     for (j=ncl+1; j<=nch; j++) 
                   2069:       m[i][j]=m[i][j-1]+nlay;
                   2070:   }
                   2071:   return m; 
                   2072:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2073:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2074:   */
                   2075: }
                   2076: 
                   2077: /*************************free ma3x ************************/
                   2078: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2079: {
                   2080:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2081:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2082:   free((FREE_ARG)(m+nrl-NR_END));
                   2083: }
                   2084: 
                   2085: /*************** function subdirf ***********/
                   2086: char *subdirf(char fileres[])
                   2087: {
                   2088:   /* Caution optionfilefiname is hidden */
                   2089:   strcpy(tmpout,optionfilefiname);
                   2090:   strcat(tmpout,"/"); /* Add to the right */
                   2091:   strcat(tmpout,fileres);
                   2092:   return tmpout;
                   2093: }
                   2094: 
                   2095: /*************** function subdirf2 ***********/
                   2096: char *subdirf2(char fileres[], char *preop)
                   2097: {
1.314     brouard  2098:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2099:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2100:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2101:   /* Caution optionfilefiname is hidden */
                   2102:   strcpy(tmpout,optionfilefiname);
                   2103:   strcat(tmpout,"/");
                   2104:   strcat(tmpout,preop);
                   2105:   strcat(tmpout,fileres);
                   2106:   return tmpout;
                   2107: }
                   2108: 
                   2109: /*************** function subdirf3 ***********/
                   2110: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2111: {
                   2112:   
                   2113:   /* Caution optionfilefiname is hidden */
                   2114:   strcpy(tmpout,optionfilefiname);
                   2115:   strcat(tmpout,"/");
                   2116:   strcat(tmpout,preop);
                   2117:   strcat(tmpout,preop2);
                   2118:   strcat(tmpout,fileres);
                   2119:   return tmpout;
                   2120: }
1.213     brouard  2121:  
                   2122: /*************** function subdirfext ***********/
                   2123: char *subdirfext(char fileres[], char *preop, char *postop)
                   2124: {
                   2125:   
                   2126:   strcpy(tmpout,preop);
                   2127:   strcat(tmpout,fileres);
                   2128:   strcat(tmpout,postop);
                   2129:   return tmpout;
                   2130: }
1.126     brouard  2131: 
1.213     brouard  2132: /*************** function subdirfext3 ***********/
                   2133: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2134: {
                   2135:   
                   2136:   /* Caution optionfilefiname is hidden */
                   2137:   strcpy(tmpout,optionfilefiname);
                   2138:   strcat(tmpout,"/");
                   2139:   strcat(tmpout,preop);
                   2140:   strcat(tmpout,fileres);
                   2141:   strcat(tmpout,postop);
                   2142:   return tmpout;
                   2143: }
                   2144:  
1.162     brouard  2145: char *asc_diff_time(long time_sec, char ascdiff[])
                   2146: {
                   2147:   long sec_left, days, hours, minutes;
                   2148:   days = (time_sec) / (60*60*24);
                   2149:   sec_left = (time_sec) % (60*60*24);
                   2150:   hours = (sec_left) / (60*60) ;
                   2151:   sec_left = (sec_left) %(60*60);
                   2152:   minutes = (sec_left) /60;
                   2153:   sec_left = (sec_left) % (60);
                   2154:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2155:   return ascdiff;
                   2156: }
                   2157: 
1.126     brouard  2158: /***************** f1dim *************************/
                   2159: extern int ncom; 
                   2160: extern double *pcom,*xicom;
                   2161: extern double (*nrfunc)(double []); 
                   2162:  
                   2163: double f1dim(double x) 
                   2164: { 
                   2165:   int j; 
                   2166:   double f;
                   2167:   double *xt; 
                   2168:  
                   2169:   xt=vector(1,ncom); 
                   2170:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2171:   f=(*nrfunc)(xt); 
                   2172:   free_vector(xt,1,ncom); 
                   2173:   return f; 
                   2174: } 
                   2175: 
                   2176: /*****************brent *************************/
                   2177: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2178: {
                   2179:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2180:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2181:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2182:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2183:    * returned function value. 
                   2184:   */
1.126     brouard  2185:   int iter; 
                   2186:   double a,b,d,etemp;
1.159     brouard  2187:   double fu=0,fv,fw,fx;
1.164     brouard  2188:   double ftemp=0.;
1.126     brouard  2189:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2190:   double e=0.0; 
                   2191:  
                   2192:   a=(ax < cx ? ax : cx); 
                   2193:   b=(ax > cx ? ax : cx); 
                   2194:   x=w=v=bx; 
                   2195:   fw=fv=fx=(*f)(x); 
                   2196:   for (iter=1;iter<=ITMAX;iter++) { 
                   2197:     xm=0.5*(a+b); 
                   2198:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2199:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2200:     printf(".");fflush(stdout);
                   2201:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2202: #ifdef DEBUGBRENT
1.126     brouard  2203:     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);
                   2204:     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);
                   2205:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2206: #endif
                   2207:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2208:       *xmin=x; 
                   2209:       return fx; 
                   2210:     } 
                   2211:     ftemp=fu;
                   2212:     if (fabs(e) > tol1) { 
                   2213:       r=(x-w)*(fx-fv); 
                   2214:       q=(x-v)*(fx-fw); 
                   2215:       p=(x-v)*q-(x-w)*r; 
                   2216:       q=2.0*(q-r); 
                   2217:       if (q > 0.0) p = -p; 
                   2218:       q=fabs(q); 
                   2219:       etemp=e; 
                   2220:       e=d; 
                   2221:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2222:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2223:       else { 
1.224     brouard  2224:                                d=p/q; 
                   2225:                                u=x+d; 
                   2226:                                if (u-a < tol2 || b-u < tol2) 
                   2227:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2228:       } 
                   2229:     } else { 
                   2230:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2231:     } 
                   2232:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2233:     fu=(*f)(u); 
                   2234:     if (fu <= fx) { 
                   2235:       if (u >= x) a=x; else b=x; 
                   2236:       SHFT(v,w,x,u) 
1.183     brouard  2237:       SHFT(fv,fw,fx,fu) 
                   2238:     } else { 
                   2239:       if (u < x) a=u; else b=u; 
                   2240:       if (fu <= fw || w == x) { 
1.224     brouard  2241:                                v=w; 
                   2242:                                w=u; 
                   2243:                                fv=fw; 
                   2244:                                fw=fu; 
1.183     brouard  2245:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2246:                                v=u; 
                   2247:                                fv=fu; 
1.183     brouard  2248:       } 
                   2249:     } 
1.126     brouard  2250:   } 
                   2251:   nrerror("Too many iterations in brent"); 
                   2252:   *xmin=x; 
                   2253:   return fx; 
                   2254: } 
                   2255: 
                   2256: /****************** mnbrak ***********************/
                   2257: 
                   2258: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2259:            double (*func)(double)) 
1.183     brouard  2260: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2261: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2262: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2263: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2264:    */
1.126     brouard  2265:   double ulim,u,r,q, dum;
                   2266:   double fu; 
1.187     brouard  2267: 
                   2268:   double scale=10.;
                   2269:   int iterscale=0;
                   2270: 
                   2271:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2272:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2273: 
                   2274: 
                   2275:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2276:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2277:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2278:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2279:   /* } */
                   2280: 
1.126     brouard  2281:   if (*fb > *fa) { 
                   2282:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2283:     SHFT(dum,*fb,*fa,dum) 
                   2284:   } 
1.126     brouard  2285:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2286:   *fc=(*func)(*cx); 
1.183     brouard  2287: #ifdef DEBUG
1.224     brouard  2288:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2289:   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  2290: #endif
1.224     brouard  2291:   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  2292:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2293:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2294:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2295:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2296:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2297:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2298:       fu=(*func)(u); 
1.163     brouard  2299: #ifdef DEBUG
                   2300:       /* f(x)=A(x-u)**2+f(u) */
                   2301:       double A, fparabu; 
                   2302:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2303:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2304:       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);
                   2305:       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  2306:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2307:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2308:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2309:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2310: #endif 
1.184     brouard  2311: #ifdef MNBRAKORIGINAL
1.183     brouard  2312: #else
1.191     brouard  2313: /*       if (fu > *fc) { */
                   2314: /* #ifdef DEBUG */
                   2315: /*       printf("mnbrak4  fu > fc \n"); */
                   2316: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2317: /* #endif */
                   2318: /*     /\* 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 *\\/  *\/ */
                   2319: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2320: /*     dum=u; /\* Shifting c and u *\/ */
                   2321: /*     u = *cx; */
                   2322: /*     *cx = dum; */
                   2323: /*     dum = fu; */
                   2324: /*     fu = *fc; */
                   2325: /*     *fc =dum; */
                   2326: /*       } else { /\* end *\/ */
                   2327: /* #ifdef DEBUG */
                   2328: /*       printf("mnbrak3  fu < fc \n"); */
                   2329: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2330: /* #endif */
                   2331: /*     dum=u; /\* Shifting c and u *\/ */
                   2332: /*     u = *cx; */
                   2333: /*     *cx = dum; */
                   2334: /*     dum = fu; */
                   2335: /*     fu = *fc; */
                   2336: /*     *fc =dum; */
                   2337: /*       } */
1.224     brouard  2338: #ifdef DEBUGMNBRAK
                   2339:                 double A, fparabu; 
                   2340:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2341:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2342:      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);
                   2343:      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  2344: #endif
1.191     brouard  2345:       dum=u; /* Shifting c and u */
                   2346:       u = *cx;
                   2347:       *cx = dum;
                   2348:       dum = fu;
                   2349:       fu = *fc;
                   2350:       *fc =dum;
1.183     brouard  2351: #endif
1.162     brouard  2352:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2353: #ifdef DEBUG
1.224     brouard  2354:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2355:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2356: #endif
1.126     brouard  2357:       fu=(*func)(u); 
                   2358:       if (fu < *fc) { 
1.183     brouard  2359: #ifdef DEBUG
1.224     brouard  2360:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2361:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2362: #endif
                   2363:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2364:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2365: #ifdef DEBUG
                   2366:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2367: #endif
                   2368:       } 
1.162     brouard  2369:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2370: #ifdef DEBUG
1.224     brouard  2371:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2372:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2373: #endif
1.126     brouard  2374:       u=ulim; 
                   2375:       fu=(*func)(u); 
1.183     brouard  2376:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2377: #ifdef DEBUG
1.224     brouard  2378:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2379:       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  2380: #endif
1.126     brouard  2381:       u=(*cx)+GOLD*(*cx-*bx); 
                   2382:       fu=(*func)(u); 
1.224     brouard  2383: #ifdef DEBUG
                   2384:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2385:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2386: #endif
1.183     brouard  2387:     } /* end tests */
1.126     brouard  2388:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2389:     SHFT(*fa,*fb,*fc,fu) 
                   2390: #ifdef DEBUG
1.224     brouard  2391:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2392:       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  2393: #endif
                   2394:   } /* 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  2395: } 
                   2396: 
                   2397: /*************** linmin ************************/
1.162     brouard  2398: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2399: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2400: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2401: the value of func at the returned location p . This is actually all accomplished by calling the
                   2402: routines mnbrak and brent .*/
1.126     brouard  2403: int ncom; 
                   2404: double *pcom,*xicom;
                   2405: double (*nrfunc)(double []); 
                   2406:  
1.224     brouard  2407: #ifdef LINMINORIGINAL
1.126     brouard  2408: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2409: #else
                   2410: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2411: #endif
1.126     brouard  2412: { 
                   2413:   double brent(double ax, double bx, double cx, 
                   2414:               double (*f)(double), double tol, double *xmin); 
                   2415:   double f1dim(double x); 
                   2416:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2417:              double *fc, double (*func)(double)); 
                   2418:   int j; 
                   2419:   double xx,xmin,bx,ax; 
                   2420:   double fx,fb,fa;
1.187     brouard  2421: 
1.203     brouard  2422: #ifdef LINMINORIGINAL
                   2423: #else
                   2424:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2425: #endif
                   2426:   
1.126     brouard  2427:   ncom=n; 
                   2428:   pcom=vector(1,n); 
                   2429:   xicom=vector(1,n); 
                   2430:   nrfunc=func; 
                   2431:   for (j=1;j<=n;j++) { 
                   2432:     pcom[j]=p[j]; 
1.202     brouard  2433:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2434:   } 
1.187     brouard  2435: 
1.203     brouard  2436: #ifdef LINMINORIGINAL
                   2437:   xx=1.;
                   2438: #else
                   2439:   axs=0.0;
                   2440:   xxs=1.;
                   2441:   do{
                   2442:     xx= xxs;
                   2443: #endif
1.187     brouard  2444:     ax=0.;
                   2445:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2446:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2447:     /* 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))   */
                   2448:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2449:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2450:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2451:     /* 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  2452: #ifdef LINMINORIGINAL
                   2453: #else
                   2454:     if (fx != fx){
1.224     brouard  2455:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2456:                        printf("|");
                   2457:                        fprintf(ficlog,"|");
1.203     brouard  2458: #ifdef DEBUGLINMIN
1.224     brouard  2459:                        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  2460: #endif
                   2461:     }
1.224     brouard  2462:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2463: #endif
                   2464:   
1.191     brouard  2465: #ifdef DEBUGLINMIN
                   2466:   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  2467:   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  2468: #endif
1.224     brouard  2469: #ifdef LINMINORIGINAL
                   2470: #else
1.317     brouard  2471:   if(fb == fx){ /* Flat function in the direction */
                   2472:     xmin=xx;
1.224     brouard  2473:     *flat=1;
1.317     brouard  2474:   }else{
1.224     brouard  2475:     *flat=0;
                   2476: #endif
                   2477:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2478:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2479:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2480:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2481:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2482:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2483: #ifdef DEBUG
1.224     brouard  2484:   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);
                   2485:   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);
                   2486: #endif
                   2487: #ifdef LINMINORIGINAL
                   2488: #else
                   2489:                        }
1.126     brouard  2490: #endif
1.191     brouard  2491: #ifdef DEBUGLINMIN
                   2492:   printf("linmin end ");
1.202     brouard  2493:   fprintf(ficlog,"linmin end ");
1.191     brouard  2494: #endif
1.126     brouard  2495:   for (j=1;j<=n;j++) { 
1.203     brouard  2496: #ifdef LINMINORIGINAL
                   2497:     xi[j] *= xmin; 
                   2498: #else
                   2499: #ifdef DEBUGLINMIN
                   2500:     if(xxs <1.0)
                   2501:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2502: #endif
                   2503:     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) */
                   2504: #ifdef DEBUGLINMIN
                   2505:     if(xxs <1.0)
                   2506:       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 );
                   2507: #endif
                   2508: #endif
1.187     brouard  2509:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2510:   } 
1.191     brouard  2511: #ifdef DEBUGLINMIN
1.203     brouard  2512:   printf("\n");
1.191     brouard  2513:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2514:   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  2515:   for (j=1;j<=n;j++) { 
1.202     brouard  2516:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2517:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2518:     if(j % ncovmodel == 0){
1.191     brouard  2519:       printf("\n");
1.202     brouard  2520:       fprintf(ficlog,"\n");
                   2521:     }
1.191     brouard  2522:   }
1.203     brouard  2523: #else
1.191     brouard  2524: #endif
1.126     brouard  2525:   free_vector(xicom,1,n); 
                   2526:   free_vector(pcom,1,n); 
                   2527: } 
                   2528: 
                   2529: 
                   2530: /*************** powell ************************/
1.162     brouard  2531: /*
1.317     brouard  2532: Minimization of a function func of n variables. Input consists in an initial starting point
                   2533: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2534: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2535: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2536: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2537: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2538:  */
1.224     brouard  2539: #ifdef LINMINORIGINAL
                   2540: #else
                   2541:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2542:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2543: #endif
1.126     brouard  2544: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2545:            double (*func)(double [])) 
                   2546: { 
1.224     brouard  2547: #ifdef LINMINORIGINAL
                   2548:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2549:              double (*func)(double [])); 
1.224     brouard  2550: #else 
1.241     brouard  2551:  void linmin(double p[], double xi[], int n, double *fret,
                   2552:             double (*func)(double []),int *flat); 
1.224     brouard  2553: #endif
1.239     brouard  2554:  int i,ibig,j,jk,k; 
1.126     brouard  2555:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2556:   double directest;
1.126     brouard  2557:   double fp,fptt;
                   2558:   double *xits;
                   2559:   int niterf, itmp;
                   2560: 
                   2561:   pt=vector(1,n); 
                   2562:   ptt=vector(1,n); 
                   2563:   xit=vector(1,n); 
                   2564:   xits=vector(1,n); 
                   2565:   *fret=(*func)(p); 
                   2566:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2567:   rcurr_time = time(NULL);
                   2568:   fp=(*fret); /* Initialisation */
1.126     brouard  2569:   for (*iter=1;;++(*iter)) { 
                   2570:     ibig=0; 
                   2571:     del=0.0; 
1.157     brouard  2572:     rlast_time=rcurr_time;
                   2573:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2574:     rcurr_time = time(NULL);  
                   2575:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2576:     /* 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); */
                   2577:     /* 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); */
                   2578:     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);
                   2579:     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  2580: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2581:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2582:     for (i=1;i<=n;i++) {
1.126     brouard  2583:       fprintf(ficrespow," %.12lf", p[i]);
                   2584:     }
1.239     brouard  2585:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2586:     printf("\n#model=  1      +     age ");
                   2587:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2588:     if(nagesqr==1){
1.241     brouard  2589:        printf("  + age*age  ");
                   2590:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2591:     }
                   2592:     for(j=1;j <=ncovmodel-2;j++){
                   2593:       if(Typevar[j]==0) {
                   2594:        printf("  +      V%d  ",Tvar[j]);
                   2595:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2596:       }else if(Typevar[j]==1) {
                   2597:        printf("  +    V%d*age ",Tvar[j]);
                   2598:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2599:       }else if(Typevar[j]==2) {
                   2600:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2601:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2602:       }
                   2603:     }
1.126     brouard  2604:     printf("\n");
1.239     brouard  2605: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2606: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2607:     fprintf(ficlog,"\n");
1.239     brouard  2608:     for(i=1,jk=1; i <=nlstate; i++){
                   2609:       for(k=1; k <=(nlstate+ndeath); k++){
                   2610:        if (k != i) {
                   2611:          printf("%d%d ",i,k);
                   2612:          fprintf(ficlog,"%d%d ",i,k);
                   2613:          for(j=1; j <=ncovmodel; j++){
                   2614:            printf("%12.7f ",p[jk]);
                   2615:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2616:            jk++; 
                   2617:          }
                   2618:          printf("\n");
                   2619:          fprintf(ficlog,"\n");
                   2620:        }
                   2621:       }
                   2622:     }
1.241     brouard  2623:     if(*iter <=3 && *iter >1){
1.157     brouard  2624:       tml = *localtime(&rcurr_time);
                   2625:       strcpy(strcurr,asctime(&tml));
                   2626:       rforecast_time=rcurr_time; 
1.126     brouard  2627:       itmp = strlen(strcurr);
                   2628:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2629:        strcurr[itmp-1]='\0';
1.162     brouard  2630:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2631:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2632:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2633:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2634:        forecast_time = *localtime(&rforecast_time);
                   2635:        strcpy(strfor,asctime(&forecast_time));
                   2636:        itmp = strlen(strfor);
                   2637:        if(strfor[itmp-1]=='\n')
                   2638:          strfor[itmp-1]='\0';
                   2639:        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);
                   2640:        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  2641:       }
                   2642:     }
1.187     brouard  2643:     for (i=1;i<=n;i++) { /* For each direction i */
                   2644:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2645:       fptt=(*fret); 
                   2646: #ifdef DEBUG
1.203     brouard  2647:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2648:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2649: #endif
1.203     brouard  2650:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2651:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2652: #ifdef LINMINORIGINAL
1.188     brouard  2653:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2654: #else
                   2655:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2656:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2657: #endif
                   2658:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2659:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2660:                                /* because that direction will be replaced unless the gain del is small */
                   2661:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2662:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2663:                                /* with the new direction. */
                   2664:                                del=fabs(fptt-(*fret)); 
                   2665:                                ibig=i; 
1.126     brouard  2666:       } 
                   2667: #ifdef DEBUG
                   2668:       printf("%d %.12e",i,(*fret));
                   2669:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2670:       for (j=1;j<=n;j++) {
1.224     brouard  2671:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2672:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2673:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2674:       }
                   2675:       for(j=1;j<=n;j++) {
1.225     brouard  2676:                                printf(" p(%d)=%.12e",j,p[j]);
                   2677:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2678:       }
                   2679:       printf("\n");
                   2680:       fprintf(ficlog,"\n");
                   2681: #endif
1.187     brouard  2682:     } /* end loop on each direction i */
                   2683:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2684:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2685:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2686:     for(j=1;j<=n;j++) {
                   2687:       if(flatdir[j] >0){
                   2688:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2689:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2690:       }
1.319     brouard  2691:       /* printf("\n"); */
                   2692:       /* fprintf(ficlog,"\n"); */
                   2693:     }
1.243     brouard  2694:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2695:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2696:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2697:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2698:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2699:       /* decreased of more than 3.84  */
                   2700:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2701:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2702:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2703:                        
1.188     brouard  2704:       /* Starting the program with initial values given by a former maximization will simply change */
                   2705:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2706:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2707:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2708: #ifdef DEBUG
                   2709:       int k[2],l;
                   2710:       k[0]=1;
                   2711:       k[1]=-1;
                   2712:       printf("Max: %.12e",(*func)(p));
                   2713:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2714:       for (j=1;j<=n;j++) {
                   2715:        printf(" %.12e",p[j]);
                   2716:        fprintf(ficlog," %.12e",p[j]);
                   2717:       }
                   2718:       printf("\n");
                   2719:       fprintf(ficlog,"\n");
                   2720:       for(l=0;l<=1;l++) {
                   2721:        for (j=1;j<=n;j++) {
                   2722:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2723:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2724:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2725:        }
                   2726:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2727:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2728:       }
                   2729: #endif
                   2730: 
                   2731:       free_vector(xit,1,n); 
                   2732:       free_vector(xits,1,n); 
                   2733:       free_vector(ptt,1,n); 
                   2734:       free_vector(pt,1,n); 
                   2735:       return; 
1.192     brouard  2736:     } /* enough precision */ 
1.240     brouard  2737:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2738:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2739:       ptt[j]=2.0*p[j]-pt[j]; 
                   2740:       xit[j]=p[j]-pt[j]; 
                   2741:       pt[j]=p[j]; 
                   2742:     } 
1.181     brouard  2743:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2744: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2745:                if (*iter <=4) {
1.225     brouard  2746: #else
                   2747: #endif
1.224     brouard  2748: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2749: #else
1.161     brouard  2750:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2751: #endif
1.162     brouard  2752:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2753:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2754:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2755:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2756:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2757:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2758:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2759:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2760:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2761:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2762:       /* mu² and del² are equal when f3=f1 */
                   2763:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2764:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2765:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2766:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2767: #ifdef NRCORIGINAL
                   2768:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2769: #else
                   2770:       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  2771:       t= t- del*SQR(fp-fptt);
1.183     brouard  2772: #endif
1.202     brouard  2773:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2774: #ifdef DEBUG
1.181     brouard  2775:       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);
                   2776:       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  2777:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2778:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2779:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2780:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2781:       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);
                   2782:       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);
                   2783: #endif
1.183     brouard  2784: #ifdef POWELLORIGINAL
                   2785:       if (t < 0.0) { /* Then we use it for new direction */
                   2786: #else
1.182     brouard  2787:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2788:                                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  2789:         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  2790:         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  2791:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2792:       } 
1.181     brouard  2793:       if (directest < 0.0) { /* Then we use it for new direction */
                   2794: #endif
1.191     brouard  2795: #ifdef DEBUGLINMIN
1.234     brouard  2796:        printf("Before linmin in direction P%d-P0\n",n);
                   2797:        for (j=1;j<=n;j++) {
                   2798:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2799:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2800:          if(j % ncovmodel == 0){
                   2801:            printf("\n");
                   2802:            fprintf(ficlog,"\n");
                   2803:          }
                   2804:        }
1.224     brouard  2805: #endif
                   2806: #ifdef LINMINORIGINAL
1.234     brouard  2807:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2808: #else
1.234     brouard  2809:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2810:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2811: #endif
1.234     brouard  2812:        
1.191     brouard  2813: #ifdef DEBUGLINMIN
1.234     brouard  2814:        for (j=1;j<=n;j++) { 
                   2815:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2816:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2817:          if(j % ncovmodel == 0){
                   2818:            printf("\n");
                   2819:            fprintf(ficlog,"\n");
                   2820:          }
                   2821:        }
1.224     brouard  2822: #endif
1.234     brouard  2823:        for (j=1;j<=n;j++) { 
                   2824:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2825:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2826:        }
1.224     brouard  2827: #ifdef LINMINORIGINAL
                   2828: #else
1.234     brouard  2829:        for (j=1, flatd=0;j<=n;j++) {
                   2830:          if(flatdir[j]>0)
                   2831:            flatd++;
                   2832:        }
                   2833:        if(flatd >0){
1.255     brouard  2834:          printf("%d flat directions: ",flatd);
                   2835:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2836:          for (j=1;j<=n;j++) { 
                   2837:            if(flatdir[j]>0){
                   2838:              printf("%d ",j);
                   2839:              fprintf(ficlog,"%d ",j);
                   2840:            }
                   2841:          }
                   2842:          printf("\n");
                   2843:          fprintf(ficlog,"\n");
1.319     brouard  2844: #ifdef FLATSUP
                   2845:           free_vector(xit,1,n); 
                   2846:           free_vector(xits,1,n); 
                   2847:           free_vector(ptt,1,n); 
                   2848:           free_vector(pt,1,n); 
                   2849:           return;
                   2850: #endif
1.234     brouard  2851:        }
1.191     brouard  2852: #endif
1.234     brouard  2853:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2854:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2855:        
1.126     brouard  2856: #ifdef DEBUG
1.234     brouard  2857:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2858:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2859:        for(j=1;j<=n;j++){
                   2860:          printf(" %lf",xit[j]);
                   2861:          fprintf(ficlog," %lf",xit[j]);
                   2862:        }
                   2863:        printf("\n");
                   2864:        fprintf(ficlog,"\n");
1.126     brouard  2865: #endif
1.192     brouard  2866:       } /* end of t or directest negative */
1.224     brouard  2867: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2868: #else
1.234     brouard  2869:       } /* end if (fptt < fp)  */
1.192     brouard  2870: #endif
1.225     brouard  2871: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2872:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2873: #else
1.224     brouard  2874: #endif
1.234     brouard  2875:                } /* loop iteration */ 
1.126     brouard  2876: } 
1.234     brouard  2877:   
1.126     brouard  2878: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2879:   
1.235     brouard  2880:   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  2881:   {
1.338     brouard  2882:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2883:      *   (and selected quantitative values in nres)
                   2884:      *  by left multiplying the unit
                   2885:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2886:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2887:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2888:      * or prevalence in state 1, prevalence in state 2, 0
                   2889:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2890:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2891:      * Output is prlim.
                   2892:      * Initial matrix pimij 
                   2893:      */
1.206     brouard  2894:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2895:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2896:   /*  0,                   0                  , 1} */
                   2897:   /*
                   2898:    * and after some iteration: */
                   2899:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2900:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2901:   /*  0,                   0                  , 1} */
                   2902:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2903:   /* {0.51571254859325999, 0.4842874514067399, */
                   2904:   /*  0.51326036147820708, 0.48673963852179264} */
                   2905:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2906:     
1.332     brouard  2907:     int i, ii,j,k, k1;
1.209     brouard  2908:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2909:   /* double **matprod2(); */ /* test */
1.218     brouard  2910:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2911:   double **newm;
1.209     brouard  2912:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2913:   int ncvloop=0;
1.288     brouard  2914:   int first=0;
1.169     brouard  2915:   
1.209     brouard  2916:   min=vector(1,nlstate);
                   2917:   max=vector(1,nlstate);
                   2918:   meandiff=vector(1,nlstate);
                   2919: 
1.218     brouard  2920:        /* Starting with matrix unity */
1.126     brouard  2921:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2922:     for (j=1;j<=nlstate+ndeath;j++){
                   2923:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2924:     }
1.169     brouard  2925:   
                   2926:   cov[1]=1.;
                   2927:   
                   2928:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2929:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2930:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2931:     ncvloop++;
1.126     brouard  2932:     newm=savm;
                   2933:     /* Covariates have to be included here again */
1.138     brouard  2934:     cov[2]=agefin;
1.319     brouard  2935:      if(nagesqr==1){
                   2936:       cov[3]= agefin*agefin;
                   2937:      }
1.332     brouard  2938:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2939:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2940:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2941:        if(Typevar[k1]==1){ /* A product with age */
                   2942:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2943:        }else{
                   2944:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2945:        }
                   2946:      }/* End of loop on model equation */
                   2947:      
                   2948: /* Start of old code (replaced by a loop on position in the model equation */
                   2949:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2950:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2951:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2952:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2953:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2954:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2955:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2956:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2957:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2958:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2959:     /*    *nsd=3                              (1)  (2)           (3) */
                   2960:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2961:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2962:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2963:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2964:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2965:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2966:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2967:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2968:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2969:     /*    *TvarsDpType */
                   2970:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2971:     /*    * nsd=1              (1)           (2) */
                   2972:     /*    *TvarsD[nsd]          3             2 */
                   2973:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2974:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2975:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2976:     /*    *\/ */
                   2977:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2978:     /*   /\* 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)); *\/ */
                   2979:     /* } */
                   2980:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2981:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2982:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2983:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2984:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2985:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2986:     /*   /\* 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]); *\/ */
                   2987:     /* } */
                   2988:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2989:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2990:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2991:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2992:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2993:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2994:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2995:     /*   } */
                   2996:     /*   /\* 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]); *\/ */
                   2997:     /* } */
                   2998:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2999:     /*   /\* 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]); *\/ */
                   3000:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3001:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3002:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3003:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3004:     /*         }else{ */
                   3005:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3006:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3007:     /*         } */
                   3008:     /*   }else{ */
                   3009:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3010:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3011:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3012:     /*         }else{ */
                   3013:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3014:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3015:     /*         } */
                   3016:     /*   } */
                   3017:     /* } /\* End product without age *\/ */
                   3018: /* ENd of old code */
1.138     brouard  3019:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3020:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3021:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3022:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3023:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3024:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3025:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3026:     
1.126     brouard  3027:     savm=oldm;
                   3028:     oldm=newm;
1.209     brouard  3029: 
                   3030:     for(j=1; j<=nlstate; j++){
                   3031:       max[j]=0.;
                   3032:       min[j]=1.;
                   3033:     }
                   3034:     for(i=1;i<=nlstate;i++){
                   3035:       sumnew=0;
                   3036:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3037:       for(j=1; j<=nlstate; j++){ 
                   3038:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3039:        max[j]=FMAX(max[j],prlim[i][j]);
                   3040:        min[j]=FMIN(min[j],prlim[i][j]);
                   3041:       }
                   3042:     }
                   3043: 
1.126     brouard  3044:     maxmax=0.;
1.209     brouard  3045:     for(j=1; j<=nlstate; j++){
                   3046:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3047:       maxmax=FMAX(maxmax,meandiff[j]);
                   3048:       /* 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  3049:     } /* j loop */
1.203     brouard  3050:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3051:     /* 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  3052:     if(maxmax < ftolpl){
1.209     brouard  3053:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3054:       free_vector(min,1,nlstate);
                   3055:       free_vector(max,1,nlstate);
                   3056:       free_vector(meandiff,1,nlstate);
1.126     brouard  3057:       return prlim;
                   3058:     }
1.288     brouard  3059:   } /* agefin loop */
1.208     brouard  3060:     /* After some age loop it doesn't converge */
1.288     brouard  3061:   if(!first){
                   3062:     first=1;
                   3063:     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  3064:     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);
                   3065:   }else if (first >=1 && first <10){
                   3066:     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);
                   3067:     first++;
                   3068:   }else if (first ==10){
                   3069:     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);
                   3070:     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");
                   3071:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3072:     first++;
1.288     brouard  3073:   }
                   3074: 
1.209     brouard  3075:   /* 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); */
                   3076:   free_vector(min,1,nlstate);
                   3077:   free_vector(max,1,nlstate);
                   3078:   free_vector(meandiff,1,nlstate);
1.208     brouard  3079:   
1.169     brouard  3080:   return prlim; /* should not reach here */
1.126     brouard  3081: }
                   3082: 
1.217     brouard  3083: 
                   3084:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3085: 
1.218     brouard  3086:  /* 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) */
                   3087:  /* 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  3088:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3089: {
1.264     brouard  3090:   /* 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  3091:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3092:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3093:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3094:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3095:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3096:   /* Initial matrix pimij */
                   3097:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3098:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3099:   /*  0,                   0                  , 1} */
                   3100:   /*
                   3101:    * and after some iteration: */
                   3102:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3103:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3104:   /*  0,                   0                  , 1} */
                   3105:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3106:   /* {0.51571254859325999, 0.4842874514067399, */
                   3107:   /*  0.51326036147820708, 0.48673963852179264} */
                   3108:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3109: 
1.332     brouard  3110:   int i, ii,j,k, k1;
1.247     brouard  3111:   int first=0;
1.217     brouard  3112:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3113:   /* double **matprod2(); */ /* test */
                   3114:   double **out, cov[NCOVMAX+1], **bmij();
                   3115:   double **newm;
1.218     brouard  3116:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3117:   double        **oldm, **savm;  /* for use */
                   3118: 
1.217     brouard  3119:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3120:   int ncvloop=0;
                   3121:   
                   3122:   min=vector(1,nlstate);
                   3123:   max=vector(1,nlstate);
                   3124:   meandiff=vector(1,nlstate);
                   3125: 
1.266     brouard  3126:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3127:   oldm=oldms; savm=savms;
                   3128:   
                   3129:   /* Starting with matrix unity */
                   3130:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3131:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3132:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3133:     }
                   3134:   
                   3135:   cov[1]=1.;
                   3136:   
                   3137:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3138:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3139:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3140:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3141:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3142:     ncvloop++;
1.218     brouard  3143:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3144:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3145:     /* Covariates have to be included here again */
                   3146:     cov[2]=agefin;
1.319     brouard  3147:     if(nagesqr==1){
1.217     brouard  3148:       cov[3]= agefin*agefin;;
1.319     brouard  3149:     }
1.332     brouard  3150:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3151:       if(Typevar[k1]==1){ /* A product with age */
                   3152:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3153:       }else{
1.332     brouard  3154:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3155:       }
1.332     brouard  3156:     }/* End of loop on model equation */
                   3157: 
                   3158: /* Old code */ 
                   3159: 
                   3160:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3161:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3162:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3163:     /*   /\* 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)); *\/ */
                   3164:     /* } */
                   3165:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3166:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3167:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3168:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3169:     /* /\* } *\/ */
                   3170:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3171:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3172:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3173:     /*   /\* 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]); *\/ */
                   3174:     /* } */
                   3175:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3176:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3177:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3178:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3179:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3180:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3181:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3182:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3183:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3184:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3185:     /*   } */
                   3186:     /*   /\* 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]); *\/ */
                   3187:     /* } */
                   3188:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3189:     /*   /\* 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]); *\/ */
                   3190:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3191:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3192:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3193:     /*         }else{ */
                   3194:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3195:     /*         } */
                   3196:     /*   }else{ */
                   3197:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3198:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3199:     /*         }else{ */
                   3200:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3201:     /*         } */
                   3202:     /*   } */
                   3203:     /* } */
1.217     brouard  3204:     
                   3205:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3206:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3207:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3208:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3209:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3210:                /* ij should be linked to the correct index of cov */
                   3211:                /* age and covariate values ij are in 'cov', but we need to pass
                   3212:                 * ij for the observed prevalence at age and status and covariate
                   3213:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3214:                 */
                   3215:     /* 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 *\/ */
                   3216:     /* 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 *\/ */
                   3217:     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  3218:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3219:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3220:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3221:     /*         printf("%d newm= ",i); */
                   3222:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3223:     /*           printf("%f ",newm[i][j]); */
                   3224:     /*         } */
                   3225:     /*         printf("oldm * "); */
                   3226:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3227:     /*           printf("%f ",oldm[i][j]); */
                   3228:     /*         } */
1.268     brouard  3229:     /*         printf(" bmmij "); */
1.266     brouard  3230:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3231:     /*           printf("%f ",pmmij[i][j]); */
                   3232:     /*         } */
                   3233:     /*         printf("\n"); */
                   3234:     /*   } */
                   3235:     /* } */
1.217     brouard  3236:     savm=oldm;
                   3237:     oldm=newm;
1.266     brouard  3238: 
1.217     brouard  3239:     for(j=1; j<=nlstate; j++){
                   3240:       max[j]=0.;
                   3241:       min[j]=1.;
                   3242:     }
                   3243:     for(j=1; j<=nlstate; j++){ 
                   3244:       for(i=1;i<=nlstate;i++){
1.234     brouard  3245:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3246:        bprlim[i][j]= newm[i][j];
                   3247:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3248:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3249:       }
                   3250:     }
1.218     brouard  3251:                
1.217     brouard  3252:     maxmax=0.;
                   3253:     for(i=1; i<=nlstate; i++){
1.318     brouard  3254:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3255:       maxmax=FMAX(maxmax,meandiff[i]);
                   3256:       /* 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  3257:     } /* i loop */
1.217     brouard  3258:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3259:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3260:     if(maxmax < ftolpl){
1.220     brouard  3261:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3262:       free_vector(min,1,nlstate);
                   3263:       free_vector(max,1,nlstate);
                   3264:       free_vector(meandiff,1,nlstate);
                   3265:       return bprlim;
                   3266:     }
1.288     brouard  3267:   } /* agefin loop */
1.217     brouard  3268:     /* After some age loop it doesn't converge */
1.288     brouard  3269:   if(!first){
1.247     brouard  3270:     first=1;
                   3271:     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\
                   3272: 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);
                   3273:   }
                   3274:   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  3275: 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);
                   3276:   /* 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); */
                   3277:   free_vector(min,1,nlstate);
                   3278:   free_vector(max,1,nlstate);
                   3279:   free_vector(meandiff,1,nlstate);
                   3280:   
                   3281:   return bprlim; /* should not reach here */
                   3282: }
                   3283: 
1.126     brouard  3284: /*************** transition probabilities ***************/ 
                   3285: 
                   3286: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3287: {
1.138     brouard  3288:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3289:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3290:      model to the ncovmodel covariates (including constant and age).
                   3291:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3292:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3293:      ncth covariate in the global vector x is given by the formula:
                   3294:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3295:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3296:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3297:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3298:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3299:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3300:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3301:   */
                   3302:   double s1, lnpijopii;
1.126     brouard  3303:   /*double t34;*/
1.164     brouard  3304:   int i,j, nc, ii, jj;
1.126     brouard  3305: 
1.223     brouard  3306:   for(i=1; i<= nlstate; i++){
                   3307:     for(j=1; j<i;j++){
                   3308:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3309:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3310:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3311:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3312:       }
                   3313:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3314:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3315:     }
                   3316:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3317:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3318:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3319:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3320:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3321:       }
                   3322:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3323:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3324:     }
                   3325:   }
1.218     brouard  3326:   
1.223     brouard  3327:   for(i=1; i<= nlstate; i++){
                   3328:     s1=0;
                   3329:     for(j=1; j<i; j++){
1.339     brouard  3330:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3331:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3332:     }
                   3333:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3334:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3335:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3336:     }
                   3337:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3338:     ps[i][i]=1./(s1+1.);
                   3339:     /* Computing other pijs */
                   3340:     for(j=1; j<i; j++)
1.325     brouard  3341:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3342:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3343:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3344:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3345:   } /* end i */
1.218     brouard  3346:   
1.223     brouard  3347:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3348:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3349:       ps[ii][jj]=0;
                   3350:       ps[ii][ii]=1;
                   3351:     }
                   3352:   }
1.294     brouard  3353: 
                   3354: 
1.223     brouard  3355:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3356:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3357:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3358:   /*   } */
                   3359:   /*   printf("\n "); */
                   3360:   /* } */
                   3361:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3362:   /*
                   3363:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3364:                goto end;*/
1.266     brouard  3365:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3366: }
                   3367: 
1.218     brouard  3368: /*************** backward transition probabilities ***************/ 
                   3369: 
                   3370:  /* 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 ) */
                   3371: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3372:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3373: {
1.302     brouard  3374:   /* 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  3375:    * 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  3376:    */
1.218     brouard  3377:   int i, ii, j,k;
1.222     brouard  3378:   
                   3379:   double **out, **pmij();
                   3380:   double sumnew=0.;
1.218     brouard  3381:   double agefin;
1.292     brouard  3382:   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  3383:   double **dnewm, **dsavm, **doldm;
                   3384:   double **bbmij;
                   3385:   
1.218     brouard  3386:   doldm=ddoldms; /* global pointers */
1.222     brouard  3387:   dnewm=ddnewms;
                   3388:   dsavm=ddsavms;
1.318     brouard  3389: 
                   3390:   /* Debug */
                   3391:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3392:   agefin=cov[2];
1.268     brouard  3393:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3394:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3395:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3396:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3397: 
                   3398:   /* P_x */
1.325     brouard  3399:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3400:   /* outputs pmmij which is a stochastic matrix in row */
                   3401: 
                   3402:   /* Diag(w_x) */
1.292     brouard  3403:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3404:   sumnew=0.;
1.269     brouard  3405:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3406:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3407:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3408:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3409:   }
                   3410:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3411:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3412:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3413:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3414:     }
                   3415:   }else{
                   3416:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3417:       for (j=1;j<=nlstate+ndeath;j++)
                   3418:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3419:     }
                   3420:     /* if(sumnew <0.9){ */
                   3421:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3422:     /* } */
                   3423:   }
                   3424:   k3=0.0;  /* We put the last diagonal to 0 */
                   3425:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3426:       doldm[ii][ii]= k3;
                   3427:   }
                   3428:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3429:   
1.292     brouard  3430:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3431:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3432: 
1.292     brouard  3433:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3434:   /* 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  3435:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3436:     sumnew=0.;
1.222     brouard  3437:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3438:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3439:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3440:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3441:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3442:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3443:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3444:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3445:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3446:        /* }else */
1.268     brouard  3447:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3448:     } /*End ii */
                   3449:   } /* 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 */
                   3450: 
1.292     brouard  3451:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3452:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3453:   /* end bmij */
1.266     brouard  3454:   return ps; /*pointer is unchanged */
1.218     brouard  3455: }
1.217     brouard  3456: /*************** transition probabilities ***************/ 
                   3457: 
1.218     brouard  3458: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3459: {
                   3460:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3461:      computes the probability to be observed in state j being in state i by appying the
                   3462:      model to the ncovmodel covariates (including constant and age).
                   3463:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3464:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3465:      ncth covariate in the global vector x is given by the formula:
                   3466:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3467:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3468:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3469:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3470:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3471:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3472:   */
                   3473:   double s1, lnpijopii;
                   3474:   /*double t34;*/
                   3475:   int i,j, nc, ii, jj;
                   3476: 
1.234     brouard  3477:   for(i=1; i<= nlstate; i++){
                   3478:     for(j=1; j<i;j++){
                   3479:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3480:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3481:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3482:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3483:       }
                   3484:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3485:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3486:     }
                   3487:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3488:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3489:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3490:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3491:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3492:       }
                   3493:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3494:     }
                   3495:   }
                   3496:   
                   3497:   for(i=1; i<= nlstate; i++){
                   3498:     s1=0;
                   3499:     for(j=1; j<i; j++){
                   3500:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3501:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3502:     }
                   3503:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3504:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3505:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3506:     }
                   3507:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3508:     ps[i][i]=1./(s1+1.);
                   3509:     /* Computing other pijs */
                   3510:     for(j=1; j<i; j++)
                   3511:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3512:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3513:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3514:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3515:   } /* end i */
                   3516:   
                   3517:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3518:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3519:       ps[ii][jj]=0;
                   3520:       ps[ii][ii]=1;
                   3521:     }
                   3522:   }
1.296     brouard  3523:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3524:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3525:     s1=0.;
                   3526:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3527:       s1+=ps[ii][jj];
                   3528:     }
                   3529:     for(ii=1; ii<= nlstate; ii++){
                   3530:       ps[ii][jj]=ps[ii][jj]/s1;
                   3531:     }
                   3532:   }
                   3533:   /* Transposition */
                   3534:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3535:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3536:       s1=ps[ii][jj];
                   3537:       ps[ii][jj]=ps[jj][ii];
                   3538:       ps[jj][ii]=s1;
                   3539:     }
                   3540:   }
                   3541:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3542:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3543:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3544:   /*   } */
                   3545:   /*   printf("\n "); */
                   3546:   /* } */
                   3547:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3548:   /*
                   3549:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3550:     goto end;*/
                   3551:   return ps;
1.217     brouard  3552: }
                   3553: 
                   3554: 
1.126     brouard  3555: /**************** Product of 2 matrices ******************/
                   3556: 
1.145     brouard  3557: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3558: {
                   3559:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3560:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3561:   /* in, b, out are matrice of pointers which should have been initialized 
                   3562:      before: only the contents of out is modified. The function returns
                   3563:      a pointer to pointers identical to out */
1.145     brouard  3564:   int i, j, k;
1.126     brouard  3565:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3566:     for(k=ncolol; k<=ncoloh; k++){
                   3567:       out[i][k]=0.;
                   3568:       for(j=ncl; j<=nch; j++)
                   3569:        out[i][k] +=in[i][j]*b[j][k];
                   3570:     }
1.126     brouard  3571:   return out;
                   3572: }
                   3573: 
                   3574: 
                   3575: /************* Higher Matrix Product ***************/
                   3576: 
1.235     brouard  3577: 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  3578: {
1.336     brouard  3579:   /* Already optimized with precov.
                   3580:      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  3581:      'nhstepm*hstepm*stepm' months (i.e. until
                   3582:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3583:      nhstepm*hstepm matrices. 
                   3584:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3585:      (typically every 2 years instead of every month which is too big 
                   3586:      for the memory).
                   3587:      Model is determined by parameters x and covariates have to be 
                   3588:      included manually here. 
                   3589: 
                   3590:      */
                   3591: 
1.330     brouard  3592:   int i, j, d, h, k, k1;
1.131     brouard  3593:   double **out, cov[NCOVMAX+1];
1.126     brouard  3594:   double **newm;
1.187     brouard  3595:   double agexact;
1.214     brouard  3596:   double agebegin, ageend;
1.126     brouard  3597: 
                   3598:   /* Hstepm could be zero and should return the unit matrix */
                   3599:   for (i=1;i<=nlstate+ndeath;i++)
                   3600:     for (j=1;j<=nlstate+ndeath;j++){
                   3601:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3602:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3603:     }
                   3604:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3605:   for(h=1; h <=nhstepm; h++){
                   3606:     for(d=1; d <=hstepm; d++){
                   3607:       newm=savm;
                   3608:       /* Covariates have to be included here again */
                   3609:       cov[1]=1.;
1.214     brouard  3610:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3611:       cov[2]=agexact;
1.319     brouard  3612:       if(nagesqr==1){
1.227     brouard  3613:        cov[3]= agexact*agexact;
1.319     brouard  3614:       }
1.330     brouard  3615:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3616:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3617:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3618:        if(Typevar[k1]==1){ /* A product with age */
                   3619:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3620:        }else{
                   3621:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3622:        }
                   3623:       }/* End of loop on model equation */
                   3624:        /* Old code */ 
                   3625: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3626: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3627: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3628: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3629: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3630: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3631: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3632: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3633: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3634: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3635: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3636: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3637: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3638: /*       /\* 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]])); *\/ */
                   3639: /*       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); */
                   3640: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3641: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3642: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3643: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3644: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3645: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3646: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3647: /*       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]]); */
                   3648: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3649: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3650: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3651: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3652: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3653: /*       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]); */
                   3654: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3655: 
                   3656: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3657: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3658: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3659: /*       /\* *\/ */
1.330     brouard  3660: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3661: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3662: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3663: /* /\*cptcovage=2                   1               2      *\/ */
                   3664: /* /\*Tage[k]=                      5               8      *\/  */
                   3665: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3666: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3667: /*       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]]); */
                   3668: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3669: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3670: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3671: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3672: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3673: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3674: /*       /\*   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); *\/ */
                   3675: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3676: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3677: /*       /\* } *\/ */
                   3678: /*       /\* 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]); *\/ */
                   3679: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3680: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3681: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3682: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3683: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3684: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3685: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3686: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3687: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3688:          
1.332     brouard  3689: /*       /\* 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])]); *\/ */
                   3690: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3691: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3692: /*       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]]); */
                   3693: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3694: 
                   3695: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3696: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3697: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3698: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3699: /*           /\* 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]])]; *\/ */
                   3700: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3701: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3702: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3703: /*       /\*   } *\/ */
                   3704: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3705: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3706: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3707: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3708: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3709: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3710: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3711: /*       /\*   } *\/ */
                   3712: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3713: /*     }/\*end of products *\/ */
                   3714:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3715:       /* for (k=1; k<=cptcovn;k++)  */
                   3716:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3717:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3718:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3719:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3720:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3721:       
                   3722:       
1.126     brouard  3723:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3724:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3725:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3726:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3727:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3728:       /* if((int)age == 70){ */
                   3729:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3730:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3731:       /*         printf("%d pmmij ",i); */
                   3732:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3733:       /*           printf("%f ",pmmij[i][j]); */
                   3734:       /*         } */
                   3735:       /*         printf(" oldm "); */
                   3736:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3737:       /*           printf("%f ",oldm[i][j]); */
                   3738:       /*         } */
                   3739:       /*         printf("\n"); */
                   3740:       /*       } */
                   3741:       /* } */
1.126     brouard  3742:       savm=oldm;
                   3743:       oldm=newm;
                   3744:     }
                   3745:     for(i=1; i<=nlstate+ndeath; i++)
                   3746:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3747:        po[i][j][h]=newm[i][j];
                   3748:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3749:       }
1.128     brouard  3750:     /*printf("h=%d ",h);*/
1.126     brouard  3751:   } /* end h */
1.267     brouard  3752:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3753:   return po;
                   3754: }
                   3755: 
1.217     brouard  3756: /************* Higher Back Matrix Product ***************/
1.218     brouard  3757: /* 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  3758: 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  3759: {
1.332     brouard  3760:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3761:      computes the transition matrix starting at age 'age' over
1.217     brouard  3762:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3763:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3764:      nhstepm*hstepm matrices.
                   3765:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3766:      (typically every 2 years instead of every month which is too big
1.217     brouard  3767:      for the memory).
1.218     brouard  3768:      Model is determined by parameters x and covariates have to be
1.266     brouard  3769:      included manually here. Then we use a call to bmij(x and cov)
                   3770:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3771:   */
1.217     brouard  3772: 
1.332     brouard  3773:   int i, j, d, h, k, k1;
1.266     brouard  3774:   double **out, cov[NCOVMAX+1], **bmij();
                   3775:   double **newm, ***newmm;
1.217     brouard  3776:   double agexact;
                   3777:   double agebegin, ageend;
1.222     brouard  3778:   double **oldm, **savm;
1.217     brouard  3779: 
1.266     brouard  3780:   newmm=po; /* To be saved */
                   3781:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3782:   /* Hstepm could be zero and should return the unit matrix */
                   3783:   for (i=1;i<=nlstate+ndeath;i++)
                   3784:     for (j=1;j<=nlstate+ndeath;j++){
                   3785:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3786:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3787:     }
                   3788:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3789:   for(h=1; h <=nhstepm; h++){
                   3790:     for(d=1; d <=hstepm; d++){
                   3791:       newm=savm;
                   3792:       /* Covariates have to be included here again */
                   3793:       cov[1]=1.;
1.271     brouard  3794:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3795:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3796:         /* Debug */
                   3797:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3798:       cov[2]=agexact;
1.332     brouard  3799:       if(nagesqr==1){
1.222     brouard  3800:        cov[3]= agexact*agexact;
1.332     brouard  3801:       }
                   3802:       /** New code */
                   3803:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3804:        if(Typevar[k1]==1){ /* A product with age */
                   3805:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3806:        }else{
1.332     brouard  3807:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3808:        }
1.332     brouard  3809:       }/* End of loop on model equation */
                   3810:       /** End of new code */
                   3811:   /** This was old code */
                   3812:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3813:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3814:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3815:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3816:       /*   /\* 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)); *\/ */
                   3817:       /* } */
                   3818:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3819:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3820:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3821:       /*       /\* 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]); *\/ */
                   3822:       /* } */
                   3823:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3824:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3825:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3826:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3827:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3828:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3829:       /*       } */
                   3830:       /*       /\* 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]); *\/ */
                   3831:       /* } */
                   3832:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3833:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3834:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3835:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3836:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3837:       /*         }else{ */
                   3838:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3839:       /*         } */
                   3840:       /*       }else{ */
                   3841:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3842:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3843:       /*         }else{ */
                   3844:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3845:       /*         } */
                   3846:       /*       } */
                   3847:       /* }                      */
                   3848:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3849:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3850: /** End of old code */
                   3851:       
1.218     brouard  3852:       /* Careful transposed matrix */
1.266     brouard  3853:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3854:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3855:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3856:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3857:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3858:       /* if((int)age == 70){ */
                   3859:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3860:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3861:       /*         printf("%d pmmij ",i); */
                   3862:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3863:       /*           printf("%f ",pmmij[i][j]); */
                   3864:       /*         } */
                   3865:       /*         printf(" oldm "); */
                   3866:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3867:       /*           printf("%f ",oldm[i][j]); */
                   3868:       /*         } */
                   3869:       /*         printf("\n"); */
                   3870:       /*       } */
                   3871:       /* } */
                   3872:       savm=oldm;
                   3873:       oldm=newm;
                   3874:     }
                   3875:     for(i=1; i<=nlstate+ndeath; i++)
                   3876:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3877:        po[i][j][h]=newm[i][j];
1.268     brouard  3878:        /* if(h==nhstepm) */
                   3879:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3880:       }
1.268     brouard  3881:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3882:   } /* end h */
1.268     brouard  3883:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3884:   return po;
                   3885: }
                   3886: 
                   3887: 
1.162     brouard  3888: #ifdef NLOPT
                   3889:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3890:   double fret;
                   3891:   double *xt;
                   3892:   int j;
                   3893:   myfunc_data *d2 = (myfunc_data *) pd;
                   3894: /* xt = (p1-1); */
                   3895:   xt=vector(1,n); 
                   3896:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3897: 
                   3898:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3899:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3900:   printf("Function = %.12lf ",fret);
                   3901:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3902:   printf("\n");
                   3903:  free_vector(xt,1,n);
                   3904:   return fret;
                   3905: }
                   3906: #endif
1.126     brouard  3907: 
                   3908: /*************** log-likelihood *************/
                   3909: double func( double *x)
                   3910: {
1.336     brouard  3911:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3912:   int ioffset=0;
1.339     brouard  3913:   int ipos=0,iposold=0,ncovv=0;
                   3914: 
1.340     brouard  3915:   double cotvarv, cotvarvold;
1.226     brouard  3916:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3917:   double **out;
                   3918:   double lli; /* Individual log likelihood */
                   3919:   int s1, s2;
1.228     brouard  3920:   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  3921: 
1.226     brouard  3922:   double bbh, survp;
                   3923:   double agexact;
1.336     brouard  3924:   double agebegin, ageend;
1.226     brouard  3925:   /*extern weight */
                   3926:   /* We are differentiating ll according to initial status */
                   3927:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3928:   /*for(i=1;i<imx;i++) 
                   3929:     printf(" %d\n",s[4][i]);
                   3930:   */
1.162     brouard  3931: 
1.226     brouard  3932:   ++countcallfunc;
1.162     brouard  3933: 
1.226     brouard  3934:   cov[1]=1.;
1.126     brouard  3935: 
1.226     brouard  3936:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3937:   ioffset=0;
1.226     brouard  3938:   if(mle==1){
                   3939:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3940:       /* Computes the values of the ncovmodel covariates of the model
                   3941:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3942:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3943:         to be observed in j being in i according to the model.
                   3944:       */
1.243     brouard  3945:       ioffset=2+nagesqr ;
1.233     brouard  3946:    /* Fixed */
1.336     brouard  3947:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3948:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3949:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3950:        /*  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  3951:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3952:        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  3953:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3954:       }
1.226     brouard  3955:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3956:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3957:         has been calculated etc */
                   3958:       /* For an individual i, wav[i] gives the number of effective waves */
                   3959:       /* We compute the contribution to Likelihood of each effective transition
                   3960:         mw[mi][i] is real wave of the mi th effectve wave */
                   3961:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3962:         s2=s[mw[mi+1][i]][i];
1.341     brouard  3963:         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  3964:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3965:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3966:       */
1.336     brouard  3967:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3968:       /* Wave varying (but not age varying) */
1.339     brouard  3969:        /* 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*\/ */
                   3970:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3971:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3972:        /* } */
1.340     brouard  3973:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3974:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3975:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   3976:          if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341     brouard  3977:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3978:          }else{ /* fixed covariate */
                   3979:            cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   3980:          }
1.339     brouard  3981:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3982:            cotvarvold=cotvarv;
                   3983:          }else{ /* A second product */
                   3984:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3985:          }
                   3986:          iposold=ipos;
1.340     brouard  3987:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  3988:        }
1.339     brouard  3989:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   3990:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3991:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3992:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3993:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3994:        /*   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]); */
                   3995:        /* } */
                   3996:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3997:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3998:        /*   /\* 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]); *\/ */
                   3999:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   4000:        /* } */
                   4001:        /* for products of time varying to be done */
1.234     brouard  4002:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4003:          for (j=1;j<=nlstate+ndeath;j++){
                   4004:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4005:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4006:          }
1.336     brouard  4007: 
                   4008:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4009:        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  4010:        for(d=0; d<dh[mi][i]; d++){
                   4011:          newm=savm;
                   4012:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4013:          cov[2]=agexact;
                   4014:          if(nagesqr==1)
                   4015:            cov[3]= agexact*agexact;  /* Should be changed here */
                   4016:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  4017:            if(!FixedV[Tvar[Tage[kk]]])
                   4018:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4019:            else
1.341     brouard  4020:              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  4021:          }
                   4022:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4023:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4024:          savm=oldm;
                   4025:          oldm=newm;
                   4026:        } /* end mult */
                   4027:        
                   4028:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4029:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4030:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4031:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4032:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4033:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4034:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4035:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4036:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4037:                                 * -stepm/2 to stepm/2 .
                   4038:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4039:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4040:                                 */
1.234     brouard  4041:        s1=s[mw[mi][i]][i];
                   4042:        s2=s[mw[mi+1][i]][i];
                   4043:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4044:        /* bias bh is positive if real duration
                   4045:         * is higher than the multiple of stepm and negative otherwise.
                   4046:         */
                   4047:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4048:        if( s2 > nlstate){ 
                   4049:          /* i.e. if s2 is a death state and if the date of death is known 
                   4050:             then the contribution to the likelihood is the probability to 
                   4051:             die between last step unit time and current  step unit time, 
                   4052:             which is also equal to probability to die before dh 
                   4053:             minus probability to die before dh-stepm . 
                   4054:             In version up to 0.92 likelihood was computed
                   4055:             as if date of death was unknown. Death was treated as any other
                   4056:             health state: the date of the interview describes the actual state
                   4057:             and not the date of a change in health state. The former idea was
                   4058:             to consider that at each interview the state was recorded
                   4059:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4060:             introduced the exact date of death then we should have modified
                   4061:             the contribution of an exact death to the likelihood. This new
                   4062:             contribution is smaller and very dependent of the step unit
                   4063:             stepm. It is no more the probability to die between last interview
                   4064:             and month of death but the probability to survive from last
                   4065:             interview up to one month before death multiplied by the
                   4066:             probability to die within a month. Thanks to Chris
                   4067:             Jackson for correcting this bug.  Former versions increased
                   4068:             mortality artificially. The bad side is that we add another loop
                   4069:             which slows down the processing. The difference can be up to 10%
                   4070:             lower mortality.
                   4071:          */
                   4072:          /* If, at the beginning of the maximization mostly, the
                   4073:             cumulative probability or probability to be dead is
                   4074:             constant (ie = 1) over time d, the difference is equal to
                   4075:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4076:             s1 at precedent wave, to be dead a month before current
                   4077:             wave is equal to probability, being at state s1 at
                   4078:             precedent wave, to be dead at mont of the current
                   4079:             wave. Then the observed probability (that this person died)
                   4080:             is null according to current estimated parameter. In fact,
                   4081:             it should be very low but not zero otherwise the log go to
                   4082:             infinity.
                   4083:          */
1.183     brouard  4084: /* #ifdef INFINITYORIGINAL */
                   4085: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4086: /* #else */
                   4087: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4088: /*         lli=log(mytinydouble); */
                   4089: /*       else */
                   4090: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4091: /* #endif */
1.226     brouard  4092:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4093:          
1.226     brouard  4094:        } else if  ( s2==-1 ) { /* alive */
                   4095:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4096:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4097:          /*survp += out[s1][j]; */
                   4098:          lli= log(survp);
                   4099:        }
1.336     brouard  4100:        /* else if  (s2==-4) {  */
                   4101:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4102:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4103:        /*   lli= log(survp);  */
                   4104:        /* }  */
                   4105:        /* else if  (s2==-5) {  */
                   4106:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4107:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4108:        /*   lli= log(survp);  */
                   4109:        /* }  */
1.226     brouard  4110:        else{
                   4111:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4112:          /*  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 */
                   4113:        } 
                   4114:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4115:        /*if(lli ==000.0)*/
1.340     brouard  4116:        /* 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  4117:        ipmx +=1;
                   4118:        sw += weight[i];
                   4119:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4120:        /* if (lli < log(mytinydouble)){ */
                   4121:        /*   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); */
                   4122:        /*   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]); */
                   4123:        /* } */
                   4124:       } /* end of wave */
                   4125:     } /* end of individual */
                   4126:   }  else if(mle==2){
                   4127:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4128:       ioffset=2+nagesqr ;
                   4129:       for (k=1; k<=ncovf;k++)
                   4130:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4131:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4132:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4133:          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  4134:        }
1.226     brouard  4135:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4136:          for (j=1;j<=nlstate+ndeath;j++){
                   4137:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4138:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4139:          }
                   4140:        for(d=0; d<=dh[mi][i]; d++){
                   4141:          newm=savm;
                   4142:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4143:          cov[2]=agexact;
                   4144:          if(nagesqr==1)
                   4145:            cov[3]= agexact*agexact;
                   4146:          for (kk=1; kk<=cptcovage;kk++) {
                   4147:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4148:          }
                   4149:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4150:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4151:          savm=oldm;
                   4152:          oldm=newm;
                   4153:        } /* end mult */
                   4154:       
                   4155:        s1=s[mw[mi][i]][i];
                   4156:        s2=s[mw[mi+1][i]][i];
                   4157:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4158:        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 */
                   4159:        ipmx +=1;
                   4160:        sw += weight[i];
                   4161:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4162:       } /* end of wave */
                   4163:     } /* end of individual */
                   4164:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4165:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4166:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4167:       for(mi=1; mi<= wav[i]-1; mi++){
                   4168:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4169:          for (j=1;j<=nlstate+ndeath;j++){
                   4170:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4171:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4172:          }
                   4173:        for(d=0; d<dh[mi][i]; d++){
                   4174:          newm=savm;
                   4175:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4176:          cov[2]=agexact;
                   4177:          if(nagesqr==1)
                   4178:            cov[3]= agexact*agexact;
                   4179:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4180:            if(!FixedV[Tvar[Tage[kk]]])
                   4181:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4182:            else
1.341     brouard  4183:              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  4184:          }
                   4185:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4186:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4187:          savm=oldm;
                   4188:          oldm=newm;
                   4189:        } /* end mult */
                   4190:       
                   4191:        s1=s[mw[mi][i]][i];
                   4192:        s2=s[mw[mi+1][i]][i];
                   4193:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4194:        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 */
                   4195:        ipmx +=1;
                   4196:        sw += weight[i];
                   4197:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4198:       } /* end of wave */
                   4199:     } /* end of individual */
                   4200:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4201:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4202:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4203:       for(mi=1; mi<= wav[i]-1; mi++){
                   4204:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4205:          for (j=1;j<=nlstate+ndeath;j++){
                   4206:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4207:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4208:          }
                   4209:        for(d=0; d<dh[mi][i]; d++){
                   4210:          newm=savm;
                   4211:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4212:          cov[2]=agexact;
                   4213:          if(nagesqr==1)
                   4214:            cov[3]= agexact*agexact;
                   4215:          for (kk=1; kk<=cptcovage;kk++) {
                   4216:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4217:          }
1.126     brouard  4218:        
1.226     brouard  4219:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4220:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4221:          savm=oldm;
                   4222:          oldm=newm;
                   4223:        } /* end mult */
                   4224:       
                   4225:        s1=s[mw[mi][i]][i];
                   4226:        s2=s[mw[mi+1][i]][i];
                   4227:        if( s2 > nlstate){ 
                   4228:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4229:        } else if  ( s2==-1 ) { /* alive */
                   4230:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4231:            survp += out[s1][j];
                   4232:          lli= log(survp);
                   4233:        }else{
                   4234:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4235:        }
                   4236:        ipmx +=1;
                   4237:        sw += weight[i];
                   4238:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4239:        /* printf("num[i]=%09ld, i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.226     brouard  4240:       } /* end of wave */
                   4241:     } /* end of individual */
                   4242:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4243:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4244:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4245:       for(mi=1; mi<= wav[i]-1; mi++){
                   4246:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4247:          for (j=1;j<=nlstate+ndeath;j++){
                   4248:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4249:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4250:          }
                   4251:        for(d=0; d<dh[mi][i]; d++){
                   4252:          newm=savm;
                   4253:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4254:          cov[2]=agexact;
                   4255:          if(nagesqr==1)
                   4256:            cov[3]= agexact*agexact;
                   4257:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4258:            if(!FixedV[Tvar[Tage[kk]]])
                   4259:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4260:            else
1.341     brouard  4261:              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  4262:          }
1.126     brouard  4263:        
1.226     brouard  4264:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4265:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4266:          savm=oldm;
                   4267:          oldm=newm;
                   4268:        } /* end mult */
                   4269:       
                   4270:        s1=s[mw[mi][i]][i];
                   4271:        s2=s[mw[mi+1][i]][i];
                   4272:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4273:        ipmx +=1;
                   4274:        sw += weight[i];
                   4275:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4276:        /*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]);*/
                   4277:       } /* end of wave */
                   4278:     } /* end of individual */
                   4279:   } /* End of if */
                   4280:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4281:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4282:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4283:   return -l;
1.126     brouard  4284: }
                   4285: 
                   4286: /*************** log-likelihood *************/
                   4287: double funcone( double *x)
                   4288: {
1.228     brouard  4289:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4290:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4291:   int ioffset=0;
1.339     brouard  4292:   int ipos=0,iposold=0,ncovv=0;
                   4293: 
1.340     brouard  4294:   double cotvarv, cotvarvold;
1.131     brouard  4295:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4296:   double **out;
                   4297:   double lli; /* Individual log likelihood */
                   4298:   double llt;
                   4299:   int s1, s2;
1.228     brouard  4300:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4301: 
1.126     brouard  4302:   double bbh, survp;
1.187     brouard  4303:   double agexact;
1.214     brouard  4304:   double agebegin, ageend;
1.126     brouard  4305:   /*extern weight */
                   4306:   /* We are differentiating ll according to initial status */
                   4307:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4308:   /*for(i=1;i<imx;i++) 
                   4309:     printf(" %d\n",s[4][i]);
                   4310:   */
                   4311:   cov[1]=1.;
                   4312: 
                   4313:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4314:   ioffset=0;
                   4315:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4316:     /* Computes the values of the ncovmodel covariates of the model
                   4317:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4318:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4319:        to be observed in j being in i according to the model.
                   4320:     */
1.243     brouard  4321:     /* ioffset=2+nagesqr+cptcovage; */
                   4322:     ioffset=2+nagesqr;
1.232     brouard  4323:     /* Fixed */
1.224     brouard  4324:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4325:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4326:     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  4327:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4328:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4329:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4330:       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  4331: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4332: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4333: /*    cov[2+6]=covar[2][i]; V2  */
                   4334: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4335: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4336: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4337: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4338: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4339: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4340:     }
1.336     brouard  4341:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4342:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4343:         has been calculated etc */
                   4344:       /* For an individual i, wav[i] gives the number of effective waves */
                   4345:       /* We compute the contribution to Likelihood of each effective transition
                   4346:         mw[mi][i] is real wave of the mi th effectve wave */
                   4347:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4348:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4349:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4350:       */
                   4351:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4352:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4353:     /*   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?)*\/ */
                   4354:     /* } */
1.231     brouard  4355:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4356:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4357:     /* } */
1.225     brouard  4358:     
1.233     brouard  4359: 
                   4360:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4361:       /* 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 */
                   4362:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4363:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4364:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4365:       /* } */
                   4366:       
                   4367:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4368:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4369:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4370:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4371:       /* We need the position of the time varying or product in the model */
                   4372:       /* 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 */            
                   4373:       /* TvarVV gives the variable name */
1.340     brouard  4374:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4375:       *      k=         1   2     3     4         5        6        7       8        9
                   4376:       *  varying            1     2                                 3       4        5
                   4377:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4378:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4379:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4380:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4381:       */
                   4382:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4383:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4384:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4385:        if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341     brouard  4386:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.340     brouard  4387:        }else{ /* fixed covariate */
                   4388:          cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   4389:        }
1.339     brouard  4390:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4391:          cotvarvold=cotvarv;
                   4392:        }else{ /* A second product */
                   4393:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4394:        }
                   4395:        iposold=ipos;
1.340     brouard  4396:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4397:        /* For products */
                   4398:       }
                   4399:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4400:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4401:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4402:       /*       /\*           1  2   3      4      5                         *\/ */
                   4403:       /*       /\*itv           1                                           *\/ */
                   4404:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4405:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4406:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4407:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4408:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4409:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4410:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4411:       /*       /\* 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]); *\/ */
                   4412:       /* } */
1.232     brouard  4413:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4414:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4415:       /*       /\* 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]); *\/ */
                   4416:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4417:       /* } */
1.126     brouard  4418:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4419:        for (j=1;j<=nlstate+ndeath;j++){
                   4420:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4421:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4422:        }
1.214     brouard  4423:       
                   4424:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4425:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4426:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4427:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4428:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4429:          and mw[mi+1][i]. dh depends on stepm.*/
                   4430:        newm=savm;
1.247     brouard  4431:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4432:        cov[2]=agexact;
                   4433:        if(nagesqr==1)
                   4434:          cov[3]= agexact*agexact;
                   4435:        for (kk=1; kk<=cptcovage;kk++) {
                   4436:          if(!FixedV[Tvar[Tage[kk]]])
                   4437:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4438:          else
1.341     brouard  4439:            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  4440:        }
                   4441:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4442:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4443:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4444:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4445:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4446:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4447:        savm=oldm;
                   4448:        oldm=newm;
1.126     brouard  4449:       } /* end mult */
1.336     brouard  4450:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4451:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4452:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4453:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4454:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4455:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4456:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4457:         * probability in order to take into account the bias as a fraction of the way
                   4458:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4459:                                 * -stepm/2 to stepm/2 .
                   4460:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4461:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4462:                                 */
1.126     brouard  4463:       s1=s[mw[mi][i]][i];
                   4464:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4465:       /* if(s2==-1){ */
1.268     brouard  4466:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4467:       /*       /\* exit(1); *\/ */
                   4468:       /* } */
1.126     brouard  4469:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4470:       /* bias is positive if real duration
                   4471:        * is higher than the multiple of stepm and negative otherwise.
                   4472:        */
                   4473:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4474:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4475:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4476:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4477:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4478:        lli= log(survp);
1.126     brouard  4479:       }else if (mle==1){
1.242     brouard  4480:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4481:       } else if(mle==2){
1.242     brouard  4482:        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  4483:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4484:        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  4485:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4486:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4487:       } else{  /* mle=0 back to 1 */
1.242     brouard  4488:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4489:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4490:       } /* End of if */
                   4491:       ipmx +=1;
                   4492:       sw += weight[i];
                   4493:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4494:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4495:       /* printf("num[i]=%09ld, i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.126     brouard  4496:       if(globpr){
1.246     brouard  4497:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4498:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4499:                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  4500:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4501:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4502:        /* %11.6f %11.6f %11.6f ", \ */
                   4503:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4504:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4505:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4506:          llt +=ll[k]*gipmx/gsw;
                   4507:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4508:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4509:        }
1.343     brouard  4510:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4511:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4512:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4513:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4514:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4515:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4516:        }
                   4517:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4518:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4519:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4520:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4521:            /* printf(" %g",cov[ioffset+ipos]); */
                   4522:          }else{
                   4523:            fprintf(ficresilk,"*");
                   4524:            /* printf("*"); */
1.342     brouard  4525:          }
1.343     brouard  4526:          iposold=ipos;
                   4527:        }
                   4528:        for (kk=1; kk<=cptcovage;kk++) {
                   4529:          if(!FixedV[Tvar[Tage[kk]]]){
                   4530:            fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]);
                   4531:            /* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4532:          }else{
                   4533:            fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4534:            /* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
1.342     brouard  4535:          }
1.343     brouard  4536:        }
                   4537:        /* printf("\n"); */
1.342     brouard  4538:        /* } /\*  End debugILK *\/ */
                   4539:        fprintf(ficresilk,"\n");
                   4540:       } /* End if globpr */
1.335     brouard  4541:     } /* end of wave */
                   4542:   } /* end of individual */
                   4543:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4544: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4545:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4546:   if(globpr==0){ /* First time we count the contributions and weights */
                   4547:     gipmx=ipmx;
                   4548:     gsw=sw;
                   4549:   }
1.343     brouard  4550:   return -l;
1.126     brouard  4551: }
                   4552: 
                   4553: 
                   4554: /*************** function likelione ***********/
1.292     brouard  4555: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4556: {
                   4557:   /* This routine should help understanding what is done with 
                   4558:      the selection of individuals/waves and
                   4559:      to check the exact contribution to the likelihood.
                   4560:      Plotting could be done.
1.342     brouard  4561:   */
                   4562:   void pstamp(FILE *ficres);
1.343     brouard  4563:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4564: 
                   4565:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4566:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4567:     strcat(fileresilk,fileresu);
1.126     brouard  4568:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4569:       printf("Problem with resultfile: %s\n", fileresilk);
                   4570:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4571:     }
1.342     brouard  4572:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4573:     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");
                   4574:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4575:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4576:     for(k=1; k<=nlstate; k++) 
                   4577:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4578:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4579: 
                   4580:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4581:       for(kf=1;kf <= ncovf; kf++){
                   4582:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4583:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4584:       }
                   4585:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4586:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4587:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4588:          /* printf(" %d",ipos); */
                   4589:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4590:        }else{
                   4591:          /* printf("*"); */
                   4592:          fprintf(ficresilk,"*");
1.343     brouard  4593:        }
1.342     brouard  4594:        iposold=ipos;
                   4595:       }
                   4596:       for (kk=1; kk<=cptcovage;kk++) {
                   4597:        if(!FixedV[Tvar[Tage[kk]]]){
                   4598:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4599:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4600:        }else{
                   4601:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4602:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4603:        }
                   4604:       }
                   4605:     /* } /\* End if debugILK *\/ */
                   4606:     /* printf("\n"); */
                   4607:     fprintf(ficresilk,"\n");
                   4608:   } /* End glogpri */
1.126     brouard  4609: 
1.292     brouard  4610:   *fretone=(*func)(p);
1.126     brouard  4611:   if(*globpri !=0){
                   4612:     fclose(ficresilk);
1.205     brouard  4613:     if (mle ==0)
                   4614:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4615:     else if(mle >=1)
                   4616:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4617:     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  4618:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4619:       
1.207     brouard  4620:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.343     brouard  4621: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4622:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4623: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4624:     
                   4625:     for (k=1; k<= nlstate ; k++) {
                   4626:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br>\n \
                   4627: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4628:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   4629:        /* kvar=Tvar[TvarFind[kf]]; */ /* variable */
                   4630:        fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   4631: <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
                   4632:       }
                   4633:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4634:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4635:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4636:        /* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   4637:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4638:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4639:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4640:          if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   4641:            fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored time varying dummy covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   4642: <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   4643:          } /* End only for dummies time varying (single?) */
                   4644:        }else{ /* Useless product */
                   4645:          /* printf("*"); */
                   4646:          /* fprintf(ficresilk,"*"); */ 
                   4647:        }
                   4648:        iposold=ipos;
                   4649:       } /* For each time varying covariate */
                   4650:     } /* End loop on states */
                   4651: 
                   4652: /*     if(debugILK){ */
                   4653: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4654: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4655: /*     for (k=1; k<= nlstate ; k++) { */
                   4656: /*       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   4657: /* <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]); */
                   4658: /*     } */
                   4659: /*       } */
                   4660: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4661: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4662: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4663: /*     /\* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); *\/ */
                   4664: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4665: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4666: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4667: /*       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /\* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  *\/ */
                   4668: /*         for (k=1; k<= nlstate ; k++) { */
                   4669: /*           fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   4670: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4671: /*         } /\* End state *\/ */
                   4672: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4673: /*     }else{ /\* Useless product *\/ */
                   4674: /*       /\* printf("*"); *\/ */
                   4675: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4676: /*     } */
                   4677: /*     iposold=ipos; */
                   4678: /*       } /\* For each time varying covariate *\/ */
                   4679: /*     }/\* End debugILK *\/ */
1.207     brouard  4680:     fflush(fichtm);
1.343     brouard  4681:   }/* End globpri */
1.126     brouard  4682:   return;
                   4683: }
                   4684: 
                   4685: 
                   4686: /*********** Maximum Likelihood Estimation ***************/
                   4687: 
                   4688: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4689: {
1.319     brouard  4690:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4691:   double **xi;
                   4692:   double fret;
                   4693:   double fretone; /* Only one call to likelihood */
                   4694:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4695: 
                   4696: #ifdef NLOPT
                   4697:   int creturn;
                   4698:   nlopt_opt opt;
                   4699:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4700:   double *lb;
                   4701:   double minf; /* the minimum objective value, upon return */
                   4702:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4703:   myfunc_data dinst, *d = &dinst;
                   4704: #endif
                   4705: 
                   4706: 
1.126     brouard  4707:   xi=matrix(1,npar,1,npar);
                   4708:   for (i=1;i<=npar;i++)
                   4709:     for (j=1;j<=npar;j++)
                   4710:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4711:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4712:   strcpy(filerespow,"POW_"); 
1.126     brouard  4713:   strcat(filerespow,fileres);
                   4714:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4715:     printf("Problem with resultfile: %s\n", filerespow);
                   4716:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4717:   }
                   4718:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4719:   for (i=1;i<=nlstate;i++)
                   4720:     for(j=1;j<=nlstate+ndeath;j++)
                   4721:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4722:   fprintf(ficrespow,"\n");
1.162     brouard  4723: #ifdef POWELL
1.319     brouard  4724: #ifdef LINMINORIGINAL
                   4725: #else /* LINMINORIGINAL */
                   4726:   
                   4727:   flatdir=ivector(1,npar); 
                   4728:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4729: #endif /*LINMINORIGINAL */
                   4730: 
                   4731: #ifdef FLATSUP
                   4732:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4733:   /* reorganizing p by suppressing flat directions */
                   4734:   for(i=1, jk=1; i <=nlstate; i++){
                   4735:     for(k=1; k <=(nlstate+ndeath); k++){
                   4736:       if (k != i) {
                   4737:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4738:         if(flatdir[jk]==1){
                   4739:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4740:         }
                   4741:         for(j=1; j <=ncovmodel; j++){
                   4742:           printf("%12.7f ",p[jk]);
                   4743:           jk++; 
                   4744:         }
                   4745:         printf("\n");
                   4746:       }
                   4747:     }
                   4748:   }
                   4749: /* skipping */
                   4750:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4751:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4752:     for(k=1; k <=(nlstate+ndeath); k++){
                   4753:       if (k != i) {
                   4754:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4755:         if(flatdir[jk]==1){
                   4756:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4757:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4758:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4759:             /*q[jjk]=p[jk];*/
                   4760:           }
                   4761:         }else{
                   4762:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4763:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4764:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4765:             /*q[jjk]=p[jk];*/
                   4766:           }
                   4767:         }
                   4768:         printf("\n");
                   4769:       }
                   4770:       fflush(stdout);
                   4771:     }
                   4772:   }
                   4773:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4774: #else  /* FLATSUP */
1.126     brouard  4775:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4776: #endif  /* FLATSUP */
                   4777: 
                   4778: #ifdef LINMINORIGINAL
                   4779: #else
                   4780:       free_ivector(flatdir,1,npar); 
                   4781: #endif  /* LINMINORIGINAL*/
                   4782: #endif /* POWELL */
1.126     brouard  4783: 
1.162     brouard  4784: #ifdef NLOPT
                   4785: #ifdef NEWUOA
                   4786:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4787: #else
                   4788:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4789: #endif
                   4790:   lb=vector(0,npar-1);
                   4791:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4792:   nlopt_set_lower_bounds(opt, lb);
                   4793:   nlopt_set_initial_step1(opt, 0.1);
                   4794:   
                   4795:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4796:   d->function = func;
                   4797:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4798:   nlopt_set_min_objective(opt, myfunc, d);
                   4799:   nlopt_set_xtol_rel(opt, ftol);
                   4800:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4801:     printf("nlopt failed! %d\n",creturn); 
                   4802:   }
                   4803:   else {
                   4804:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4805:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4806:     iter=1; /* not equal */
                   4807:   }
                   4808:   nlopt_destroy(opt);
                   4809: #endif
1.319     brouard  4810: #ifdef FLATSUP
                   4811:   /* npared = npar -flatd/ncovmodel; */
                   4812:   /* xired= matrix(1,npared,1,npared); */
                   4813:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4814:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4815:   /* free_matrix(xire,1,npared,1,npared); */
                   4816: #else  /* FLATSUP */
                   4817: #endif /* FLATSUP */
1.126     brouard  4818:   free_matrix(xi,1,npar,1,npar);
                   4819:   fclose(ficrespow);
1.203     brouard  4820:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4821:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4822:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4823: 
                   4824: }
                   4825: 
                   4826: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4827: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4828: {
                   4829:   double  **a,**y,*x,pd;
1.203     brouard  4830:   /* double **hess; */
1.164     brouard  4831:   int i, j;
1.126     brouard  4832:   int *indx;
                   4833: 
                   4834:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4835:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4836:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4837:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4838:   double gompertz(double p[]);
1.203     brouard  4839:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4840: 
                   4841:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4842:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4843:   for (i=1;i<=npar;i++){
1.203     brouard  4844:     printf("%d-",i);fflush(stdout);
                   4845:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4846:    
                   4847:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4848:     
                   4849:     /*  printf(" %f ",p[i]);
                   4850:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4851:   }
                   4852:   
                   4853:   for (i=1;i<=npar;i++) {
                   4854:     for (j=1;j<=npar;j++)  {
                   4855:       if (j>i) { 
1.203     brouard  4856:        printf(".%d-%d",i,j);fflush(stdout);
                   4857:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4858:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4859:        
                   4860:        hess[j][i]=hess[i][j];    
                   4861:        /*printf(" %lf ",hess[i][j]);*/
                   4862:       }
                   4863:     }
                   4864:   }
                   4865:   printf("\n");
                   4866:   fprintf(ficlog,"\n");
                   4867: 
                   4868:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4869:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4870:   
                   4871:   a=matrix(1,npar,1,npar);
                   4872:   y=matrix(1,npar,1,npar);
                   4873:   x=vector(1,npar);
                   4874:   indx=ivector(1,npar);
                   4875:   for (i=1;i<=npar;i++)
                   4876:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4877:   ludcmp(a,npar,indx,&pd);
                   4878: 
                   4879:   for (j=1;j<=npar;j++) {
                   4880:     for (i=1;i<=npar;i++) x[i]=0;
                   4881:     x[j]=1;
                   4882:     lubksb(a,npar,indx,x);
                   4883:     for (i=1;i<=npar;i++){ 
                   4884:       matcov[i][j]=x[i];
                   4885:     }
                   4886:   }
                   4887: 
                   4888:   printf("\n#Hessian matrix#\n");
                   4889:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4890:   for (i=1;i<=npar;i++) { 
                   4891:     for (j=1;j<=npar;j++) { 
1.203     brouard  4892:       printf("%.6e ",hess[i][j]);
                   4893:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4894:     }
                   4895:     printf("\n");
                   4896:     fprintf(ficlog,"\n");
                   4897:   }
                   4898: 
1.203     brouard  4899:   /* printf("\n#Covariance matrix#\n"); */
                   4900:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4901:   /* for (i=1;i<=npar;i++) {  */
                   4902:   /*   for (j=1;j<=npar;j++) {  */
                   4903:   /*     printf("%.6e ",matcov[i][j]); */
                   4904:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4905:   /*   } */
                   4906:   /*   printf("\n"); */
                   4907:   /*   fprintf(ficlog,"\n"); */
                   4908:   /* } */
                   4909: 
1.126     brouard  4910:   /* Recompute Inverse */
1.203     brouard  4911:   /* for (i=1;i<=npar;i++) */
                   4912:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4913:   /* ludcmp(a,npar,indx,&pd); */
                   4914: 
                   4915:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4916: 
                   4917:   /* for (j=1;j<=npar;j++) { */
                   4918:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4919:   /*   x[j]=1; */
                   4920:   /*   lubksb(a,npar,indx,x); */
                   4921:   /*   for (i=1;i<=npar;i++){  */
                   4922:   /*     y[i][j]=x[i]; */
                   4923:   /*     printf("%.3e ",y[i][j]); */
                   4924:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4925:   /*   } */
                   4926:   /*   printf("\n"); */
                   4927:   /*   fprintf(ficlog,"\n"); */
                   4928:   /* } */
                   4929: 
                   4930:   /* Verifying the inverse matrix */
                   4931: #ifdef DEBUGHESS
                   4932:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4933: 
1.203     brouard  4934:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4935:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4936: 
                   4937:   for (j=1;j<=npar;j++) {
                   4938:     for (i=1;i<=npar;i++){ 
1.203     brouard  4939:       printf("%.2f ",y[i][j]);
                   4940:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4941:     }
                   4942:     printf("\n");
                   4943:     fprintf(ficlog,"\n");
                   4944:   }
1.203     brouard  4945: #endif
1.126     brouard  4946: 
                   4947:   free_matrix(a,1,npar,1,npar);
                   4948:   free_matrix(y,1,npar,1,npar);
                   4949:   free_vector(x,1,npar);
                   4950:   free_ivector(indx,1,npar);
1.203     brouard  4951:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4952: 
                   4953: 
                   4954: }
                   4955: 
                   4956: /*************** hessian matrix ****************/
                   4957: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4958: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4959:   int i;
                   4960:   int l=1, lmax=20;
1.203     brouard  4961:   double k1,k2, res, fx;
1.132     brouard  4962:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4963:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4964:   int k=0,kmax=10;
                   4965:   double l1;
                   4966: 
                   4967:   fx=func(x);
                   4968:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4969:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4970:     l1=pow(10,l);
                   4971:     delts=delt;
                   4972:     for(k=1 ; k <kmax; k=k+1){
                   4973:       delt = delta*(l1*k);
                   4974:       p2[theta]=x[theta] +delt;
1.145     brouard  4975:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4976:       p2[theta]=x[theta]-delt;
                   4977:       k2=func(p2)-fx;
                   4978:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4979:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4980:       
1.203     brouard  4981: #ifdef DEBUGHESSII
1.126     brouard  4982:       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);
                   4983:       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);
                   4984: #endif
                   4985:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4986:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4987:        k=kmax;
                   4988:       }
                   4989:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4990:        k=kmax; l=lmax*10;
1.126     brouard  4991:       }
                   4992:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4993:        delts=delt;
                   4994:       }
1.203     brouard  4995:     } /* End loop k */
1.126     brouard  4996:   }
                   4997:   delti[theta]=delts;
                   4998:   return res; 
                   4999:   
                   5000: }
                   5001: 
1.203     brouard  5002: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5003: {
                   5004:   int i;
1.164     brouard  5005:   int l=1, lmax=20;
1.126     brouard  5006:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5007:   double p2[MAXPARM+1];
1.203     brouard  5008:   int k, kmax=1;
                   5009:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5010: 
                   5011:   int firstime=0;
1.203     brouard  5012:   
1.126     brouard  5013:   fx=func(x);
1.203     brouard  5014:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5015:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5016:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5017:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5018:     k1=func(p2)-fx;
                   5019:   
1.203     brouard  5020:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5021:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5022:     k2=func(p2)-fx;
                   5023:   
1.203     brouard  5024:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5025:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5026:     k3=func(p2)-fx;
                   5027:   
1.203     brouard  5028:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5029:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5030:     k4=func(p2)-fx;
1.203     brouard  5031:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5032:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5033:       firstime=1;
1.203     brouard  5034:       kmax=kmax+10;
1.208     brouard  5035:     }
                   5036:     if(kmax >=10 || firstime ==1){
1.246     brouard  5037:       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);
                   5038:       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  5039:       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);
                   5040:       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);
                   5041:     }
                   5042: #ifdef DEBUGHESSIJ
                   5043:     v1=hess[thetai][thetai];
                   5044:     v2=hess[thetaj][thetaj];
                   5045:     cv12=res;
                   5046:     /* Computing eigen value of Hessian matrix */
                   5047:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5048:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5049:     if ((lc2 <0) || (lc1 <0) ){
                   5050:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5051:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5052:       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);
                   5053:       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);
                   5054:     }
1.126     brouard  5055: #endif
                   5056:   }
                   5057:   return res;
                   5058: }
                   5059: 
1.203     brouard  5060:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5061: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5062: /* { */
                   5063: /*   int i; */
                   5064: /*   int l=1, lmax=20; */
                   5065: /*   double k1,k2,k3,k4,res,fx; */
                   5066: /*   double p2[MAXPARM+1]; */
                   5067: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5068: /*   int k=0,kmax=10; */
                   5069: /*   double l1; */
                   5070:   
                   5071: /*   fx=func(x); */
                   5072: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5073: /*     l1=pow(10,l); */
                   5074: /*     delts=delt; */
                   5075: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5076: /*       delt = delti*(l1*k); */
                   5077: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5078: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5079: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5080: /*       k1=func(p2)-fx; */
                   5081:       
                   5082: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5083: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5084: /*       k2=func(p2)-fx; */
                   5085:       
                   5086: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5087: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5088: /*       k3=func(p2)-fx; */
                   5089:       
                   5090: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5091: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5092: /*       k4=func(p2)-fx; */
                   5093: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5094: /* #ifdef DEBUGHESSIJ */
                   5095: /*       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); */
                   5096: /*       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); */
                   5097: /* #endif */
                   5098: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5099: /*     k=kmax; */
                   5100: /*       } */
                   5101: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5102: /*     k=kmax; l=lmax*10; */
                   5103: /*       } */
                   5104: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5105: /*     delts=delt; */
                   5106: /*       } */
                   5107: /*     } /\* End loop k *\/ */
                   5108: /*   } */
                   5109: /*   delti[theta]=delts; */
                   5110: /*   return res;  */
                   5111: /* } */
                   5112: 
                   5113: 
1.126     brouard  5114: /************** Inverse of matrix **************/
                   5115: void ludcmp(double **a, int n, int *indx, double *d) 
                   5116: { 
                   5117:   int i,imax,j,k; 
                   5118:   double big,dum,sum,temp; 
                   5119:   double *vv; 
                   5120:  
                   5121:   vv=vector(1,n); 
                   5122:   *d=1.0; 
                   5123:   for (i=1;i<=n;i++) { 
                   5124:     big=0.0; 
                   5125:     for (j=1;j<=n;j++) 
                   5126:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5127:     if (big == 0.0){
                   5128:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5129:       for (j=1;j<=n;j++) {
                   5130:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5131:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5132:       }
                   5133:       fflush(ficlog);
                   5134:       fclose(ficlog);
                   5135:       nrerror("Singular matrix in routine ludcmp"); 
                   5136:     }
1.126     brouard  5137:     vv[i]=1.0/big; 
                   5138:   } 
                   5139:   for (j=1;j<=n;j++) { 
                   5140:     for (i=1;i<j;i++) { 
                   5141:       sum=a[i][j]; 
                   5142:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5143:       a[i][j]=sum; 
                   5144:     } 
                   5145:     big=0.0; 
                   5146:     for (i=j;i<=n;i++) { 
                   5147:       sum=a[i][j]; 
                   5148:       for (k=1;k<j;k++) 
                   5149:        sum -= a[i][k]*a[k][j]; 
                   5150:       a[i][j]=sum; 
                   5151:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5152:        big=dum; 
                   5153:        imax=i; 
                   5154:       } 
                   5155:     } 
                   5156:     if (j != imax) { 
                   5157:       for (k=1;k<=n;k++) { 
                   5158:        dum=a[imax][k]; 
                   5159:        a[imax][k]=a[j][k]; 
                   5160:        a[j][k]=dum; 
                   5161:       } 
                   5162:       *d = -(*d); 
                   5163:       vv[imax]=vv[j]; 
                   5164:     } 
                   5165:     indx[j]=imax; 
                   5166:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5167:     if (j != n) { 
                   5168:       dum=1.0/(a[j][j]); 
                   5169:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5170:     } 
                   5171:   } 
                   5172:   free_vector(vv,1,n);  /* Doesn't work */
                   5173: ;
                   5174: } 
                   5175: 
                   5176: void lubksb(double **a, int n, int *indx, double b[]) 
                   5177: { 
                   5178:   int i,ii=0,ip,j; 
                   5179:   double sum; 
                   5180:  
                   5181:   for (i=1;i<=n;i++) { 
                   5182:     ip=indx[i]; 
                   5183:     sum=b[ip]; 
                   5184:     b[ip]=b[i]; 
                   5185:     if (ii) 
                   5186:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5187:     else if (sum) ii=i; 
                   5188:     b[i]=sum; 
                   5189:   } 
                   5190:   for (i=n;i>=1;i--) { 
                   5191:     sum=b[i]; 
                   5192:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5193:     b[i]=sum/a[i][i]; 
                   5194:   } 
                   5195: } 
                   5196: 
                   5197: void pstamp(FILE *fichier)
                   5198: {
1.196     brouard  5199:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5200: }
                   5201: 
1.297     brouard  5202: void date2dmy(double date,double *day, double *month, double *year){
                   5203:   double yp=0., yp1=0., yp2=0.;
                   5204:   
                   5205:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5206:                        fractional in yp1 */
                   5207:   *year=yp;
                   5208:   yp2=modf((yp1*12),&yp);
                   5209:   *month=yp;
                   5210:   yp1=modf((yp2*30.5),&yp);
                   5211:   *day=yp;
                   5212:   if(*day==0) *day=1;
                   5213:   if(*month==0) *month=1;
                   5214: }
                   5215: 
1.253     brouard  5216: 
                   5217: 
1.126     brouard  5218: /************ Frequencies ********************/
1.251     brouard  5219: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5220:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5221:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5222: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5223:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5224:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5225:   int iind=0, iage=0;
                   5226:   int mi; /* Effective wave */
                   5227:   int first;
                   5228:   double ***freq; /* Frequencies */
1.268     brouard  5229:   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 */
                   5230:   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  5231:   double *meanq, *stdq, *idq;
1.226     brouard  5232:   double **meanqt;
                   5233:   double *pp, **prop, *posprop, *pospropt;
                   5234:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5235:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5236:   double agebegin, ageend;
                   5237:     
                   5238:   pp=vector(1,nlstate);
1.251     brouard  5239:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5240:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5241:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5242:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5243:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5244:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5245:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5246:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5247:   strcpy(fileresp,"P_");
                   5248:   strcat(fileresp,fileresu);
                   5249:   /*strcat(fileresphtm,fileresu);*/
                   5250:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5251:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5252:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5253:     exit(0);
                   5254:   }
1.240     brouard  5255:   
1.226     brouard  5256:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5257:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5258:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5259:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5260:     fflush(ficlog);
                   5261:     exit(70); 
                   5262:   }
                   5263:   else{
                   5264:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5265: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5266: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5267:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5268:   }
1.319     brouard  5269:   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  5270:   
1.226     brouard  5271:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5272:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5273:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5274:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5275:     fflush(ficlog);
                   5276:     exit(70); 
1.240     brouard  5277:   } else{
1.226     brouard  5278:     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  5279: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5280: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5281:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5282:   }
1.319     brouard  5283:   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  5284:   
1.253     brouard  5285:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5286:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5287:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5288:   j1=0;
1.126     brouard  5289:   
1.227     brouard  5290:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5291:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5292:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5293:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5294:   
                   5295:   
1.226     brouard  5296:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5297:      reference=low_education V1=0,V2=0
                   5298:      med_educ                V1=1 V2=0, 
                   5299:      high_educ               V1=0 V2=1
1.330     brouard  5300:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5301:   */
1.249     brouard  5302:   dateintsum=0;
                   5303:   k2cpt=0;
                   5304: 
1.253     brouard  5305:   if(cptcoveff == 0 )
1.265     brouard  5306:     nl=1;  /* Constant and age model only */
1.253     brouard  5307:   else
                   5308:     nl=2;
1.265     brouard  5309: 
                   5310:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5311:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5312:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5313:    *     freq[s1][s2][iage] =0.
                   5314:    *     Loop on iind
                   5315:    *       ++freq[s1][s2][iage] weighted
                   5316:    *     end iind
                   5317:    *     if covariate and j!0
                   5318:    *       headers Variable on one line
                   5319:    *     endif cov j!=0
                   5320:    *     header of frequency table by age
                   5321:    *     Loop on age
                   5322:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5323:    *       pos+=freq[s1][s2][iage] weighted
                   5324:    *       Loop on s1 initial state
                   5325:    *         fprintf(ficresp
                   5326:    *       end s1
                   5327:    *     end age
                   5328:    *     if j!=0 computes starting values
                   5329:    *     end compute starting values
                   5330:    *   end j1
                   5331:    * end nl 
                   5332:    */
1.253     brouard  5333:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5334:     if(nj==1)
                   5335:       j=0;  /* First pass for the constant */
1.265     brouard  5336:     else{
1.335     brouard  5337:       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  5338:     }
1.251     brouard  5339:     first=1;
1.332     brouard  5340:     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  5341:       posproptt=0.;
1.330     brouard  5342:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5343:        scanf("%d", i);*/
                   5344:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5345:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5346:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5347:            freq[i][s2][m]=0;
1.251     brouard  5348:       
                   5349:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5350:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5351:          prop[i][m]=0;
                   5352:        posprop[i]=0;
                   5353:        pospropt[i]=0;
                   5354:       }
1.283     brouard  5355:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5356:         idq[z1]=0.;
                   5357:         meanq[z1]=0.;
                   5358:         stdq[z1]=0.;
1.283     brouard  5359:       }
                   5360:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5361:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5362:       /*         meanqt[m][z1]=0.; */
                   5363:       /*       } */
                   5364:       /* }       */
1.251     brouard  5365:       /* dateintsum=0; */
                   5366:       /* k2cpt=0; */
                   5367:       
1.265     brouard  5368:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5369:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5370:        bool=1;
                   5371:        if(j !=0){
                   5372:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5373:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5374:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5375:                /* if(Tvaraff[z1] ==-20){ */
                   5376:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5377:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5378:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5379:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5380:                /* 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); */
                   5381:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5382:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5383:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5384:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5385:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5386:                  /* 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", */
                   5387:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5388:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5389:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5390:                } /* Onlyf fixed */
                   5391:              } /* end z1 */
1.335     brouard  5392:            } /* cptcoveff > 0 */
1.251     brouard  5393:          } /* end any */
                   5394:        }/* end j==0 */
1.265     brouard  5395:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5396:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5397:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5398:            m=mw[mi][iind];
                   5399:            if(j!=0){
                   5400:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5401:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5402:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5403:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5404:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5405:                    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  5406:                                                                                      value is -1, we don't select. It differs from the 
                   5407:                                                                                      constant and age model which counts them. */
                   5408:                      bool=0; /* not selected */
                   5409:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5410:                    /* i1=Tvaraff[z1]; */
                   5411:                    /* i2=TnsdVar[i1]; */
                   5412:                    /* i3=nbcode[i1][i2]; */
                   5413:                    /* i4=covar[i1][iind]; */
                   5414:                    /* if(i4 != i3){ */
                   5415:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5416:                      bool=0;
                   5417:                    }
                   5418:                  }
                   5419:                }
                   5420:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5421:            } /* end j==0 */
                   5422:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5423:            if(bool==1){ /*Selected */
1.251     brouard  5424:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5425:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5426:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5427:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5428:              if(m >=firstpass && m <=lastpass){
                   5429:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5430:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5431:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5432:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5433:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5434:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5435:                if (m<lastpass) {
                   5436:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5437:                  /*   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]); */
                   5438:                  if(s[m][iind]==-1)
                   5439:                    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.));
                   5440:                  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  5441:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5442:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5443:                      idq[z1]=idq[z1]+weight[iind];
                   5444:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5445:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5446:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5447:                    }
1.284     brouard  5448:                  }
1.251     brouard  5449:                  /* if((int)agev[m][iind] == 55) */
                   5450:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5451:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5452:                  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  5453:                }
1.251     brouard  5454:              } /* end if between passes */  
                   5455:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5456:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5457:                k2cpt++;
                   5458:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5459:              }
1.251     brouard  5460:            }else{
                   5461:              bool=1;
                   5462:            }/* end bool 2 */
                   5463:          } /* end m */
1.284     brouard  5464:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5465:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5466:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5467:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5468:          /* } */
1.251     brouard  5469:        } /* end bool */
                   5470:       } /* end iind = 1 to imx */
1.319     brouard  5471:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5472:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5473:       
                   5474:       
                   5475:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5476:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5477:         pstamp(ficresp);
1.335     brouard  5478:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5479:         pstamp(ficresp);
1.251     brouard  5480:        printf( "\n#********** Variable "); 
                   5481:        fprintf(ficresp, "\n#********** Variable "); 
                   5482:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5483:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5484:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5485:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5486:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5487:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5488:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5489:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5490:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5491:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5492:          }else{
1.330     brouard  5493:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5494:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5495:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5496:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5497:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5498:          }
                   5499:        }
                   5500:        printf( "**********\n#");
                   5501:        fprintf(ficresp, "**********\n#");
                   5502:        fprintf(ficresphtm, "**********</h3>\n");
                   5503:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5504:        fprintf(ficlog, "**********\n");
                   5505:       }
1.284     brouard  5506:       /*
                   5507:        Printing means of quantitative variables if any
                   5508:       */
                   5509:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5510:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5511:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5512:        if(weightopt==1){
                   5513:          printf(" Weighted mean and standard deviation of");
                   5514:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5515:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5516:        }
1.311     brouard  5517:        /* mu = \frac{w x}{\sum w}
                   5518:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5519:        */
                   5520:        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]));
                   5521:        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]));
                   5522:        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  5523:       }
                   5524:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5525:       /*       for(m=1;m<=lastpass;m++){ */
                   5526:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5527:       /*   } */
                   5528:       /* } */
1.283     brouard  5529: 
1.251     brouard  5530:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5531:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5532:         fprintf(ficresp, " Age");
1.335     brouard  5533:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5534:          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]]);
                   5535:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5536:        }
1.251     brouard  5537:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5538:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5539:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5540:       }
1.335     brouard  5541:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5542:       fprintf(ficresphtm, "\n");
                   5543:       
                   5544:       /* Header of frequency table by age */
                   5545:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5546:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5547:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5548:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5549:          if(s2!=0 && m!=0)
                   5550:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5551:        }
1.226     brouard  5552:       }
1.251     brouard  5553:       fprintf(ficresphtmfr, "\n");
                   5554:     
                   5555:       /* For each age */
                   5556:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5557:        fprintf(ficresphtm,"<tr>");
                   5558:        if(iage==iagemax+1){
                   5559:          fprintf(ficlog,"1");
                   5560:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5561:        }else if(iage==iagemax+2){
                   5562:          fprintf(ficlog,"0");
                   5563:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5564:        }else if(iage==iagemax+3){
                   5565:          fprintf(ficlog,"Total");
                   5566:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5567:        }else{
1.240     brouard  5568:          if(first==1){
1.251     brouard  5569:            first=0;
                   5570:            printf("See log file for details...\n");
                   5571:          }
                   5572:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5573:          fprintf(ficlog,"Age %d", iage);
                   5574:        }
1.265     brouard  5575:        for(s1=1; s1 <=nlstate ; s1++){
                   5576:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5577:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5578:        }
1.265     brouard  5579:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5580:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5581:            pos += freq[s1][m][iage];
                   5582:          if(pp[s1]>=1.e-10){
1.251     brouard  5583:            if(first==1){
1.265     brouard  5584:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5585:            }
1.265     brouard  5586:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5587:          }else{
                   5588:            if(first==1)
1.265     brouard  5589:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5590:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5591:          }
                   5592:        }
                   5593:       
1.265     brouard  5594:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5595:          /* posprop[s1]=0; */
                   5596:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5597:            pp[s1] += freq[s1][m][iage];
                   5598:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5599:       
                   5600:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5601:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5602:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5603:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5604:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5605:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5606:        }
                   5607:        
                   5608:        /* Writing ficresp */
1.335     brouard  5609:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5610:           if( iage <= iagemax){
                   5611:            fprintf(ficresp," %d",iage);
                   5612:           }
                   5613:         }else if( nj==2){
                   5614:           if( iage <= iagemax){
                   5615:            fprintf(ficresp," %d",iage);
1.335     brouard  5616:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5617:           }
1.240     brouard  5618:        }
1.265     brouard  5619:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5620:          if(pos>=1.e-5){
1.251     brouard  5621:            if(first==1)
1.265     brouard  5622:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5623:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5624:          }else{
                   5625:            if(first==1)
1.265     brouard  5626:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5627:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5628:          }
                   5629:          if( iage <= iagemax){
                   5630:            if(pos>=1.e-5){
1.335     brouard  5631:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5632:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5633:               }else if( nj==2){
                   5634:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5635:               }
                   5636:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5637:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5638:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5639:            } else{
1.335     brouard  5640:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5641:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5642:            }
1.240     brouard  5643:          }
1.265     brouard  5644:          pospropt[s1] +=posprop[s1];
                   5645:        } /* end loop s1 */
1.251     brouard  5646:        /* pospropt=0.; */
1.265     brouard  5647:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5648:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5649:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5650:              if(first==1){
1.265     brouard  5651:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5652:              }
1.265     brouard  5653:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5654:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5655:            }
1.265     brouard  5656:            if(s1!=0 && m!=0)
                   5657:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5658:          }
1.265     brouard  5659:        } /* end loop s1 */
1.251     brouard  5660:        posproptt=0.; 
1.265     brouard  5661:        for(s1=1; s1 <=nlstate; s1++){
                   5662:          posproptt += pospropt[s1];
1.251     brouard  5663:        }
                   5664:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5665:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5666:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5667:          if(iage <= iagemax)
                   5668:            fprintf(ficresp,"\n");
1.240     brouard  5669:        }
1.251     brouard  5670:        if(first==1)
                   5671:          printf("Others in log...\n");
                   5672:        fprintf(ficlog,"\n");
                   5673:       } /* end loop age iage */
1.265     brouard  5674:       
1.251     brouard  5675:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5676:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5677:        if(posproptt < 1.e-5){
1.265     brouard  5678:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5679:        }else{
1.265     brouard  5680:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5681:        }
1.226     brouard  5682:       }
1.251     brouard  5683:       fprintf(ficresphtm,"</tr>\n");
                   5684:       fprintf(ficresphtm,"</table>\n");
                   5685:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5686:       if(posproptt < 1.e-5){
1.251     brouard  5687:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5688:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5689:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5690:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5691:        invalidvarcomb[j1]=1;
1.226     brouard  5692:       }else{
1.338     brouard  5693:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5694:        invalidvarcomb[j1]=0;
1.226     brouard  5695:       }
1.251     brouard  5696:       fprintf(ficresphtmfr,"</table>\n");
                   5697:       fprintf(ficlog,"\n");
                   5698:       if(j!=0){
                   5699:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5700:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5701:          for(k=1; k <=(nlstate+ndeath); k++){
                   5702:            if (k != i) {
1.265     brouard  5703:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5704:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5705:                  if(j1==1){ /* All dummy covariates to zero */
                   5706:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5707:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5708:                    printf("%d%d ",i,k);
                   5709:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5710:                    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]));
                   5711:                    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]));
                   5712:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5713:                  }
1.253     brouard  5714:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5715:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5716:                    x[iage]= (double)iage;
                   5717:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5718:                    /* 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  5719:                  }
1.268     brouard  5720:                  /* Some are not finite, but linreg will ignore these ages */
                   5721:                  no=0;
1.253     brouard  5722:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5723:                  pstart[s1]=b;
                   5724:                  pstart[s1-1]=a;
1.252     brouard  5725:                }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 */ 
                   5726:                  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]);
                   5727:                  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  5728:                  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  5729:                  printf("%d%d ",i,k);
                   5730:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5731:                  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  5732:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5733:                  ;
                   5734:                }
                   5735:                /* printf("%12.7f )", param[i][jj][k]); */
                   5736:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5737:                s1++; 
1.251     brouard  5738:              } /* end jj */
                   5739:            } /* end k!= i */
                   5740:          } /* end k */
1.265     brouard  5741:        } /* end i, s1 */
1.251     brouard  5742:       } /* end j !=0 */
                   5743:     } /* end selected combination of covariate j1 */
                   5744:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5745:       printf("#Freqsummary: Starting values for the constants:\n");
                   5746:       fprintf(ficlog,"\n");
1.265     brouard  5747:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5748:        for(k=1; k <=(nlstate+ndeath); k++){
                   5749:          if (k != i) {
                   5750:            printf("%d%d ",i,k);
                   5751:            fprintf(ficlog,"%d%d ",i,k);
                   5752:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5753:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5754:              if(jj==1){ /* Age has to be done */
1.265     brouard  5755:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5756:                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]));
                   5757:                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  5758:              }
                   5759:              /* printf("%12.7f )", param[i][jj][k]); */
                   5760:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5761:              s1++; 
1.250     brouard  5762:            }
1.251     brouard  5763:            printf("\n");
                   5764:            fprintf(ficlog,"\n");
1.250     brouard  5765:          }
                   5766:        }
1.284     brouard  5767:       } /* end of state i */
1.251     brouard  5768:       printf("#Freqsummary\n");
                   5769:       fprintf(ficlog,"\n");
1.265     brouard  5770:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5771:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5772:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5773:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5774:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5775:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5776:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5777:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5778:          /* } */
                   5779:        }
1.265     brouard  5780:       } /* end loop s1 */
1.251     brouard  5781:       
                   5782:       printf("\n");
                   5783:       fprintf(ficlog,"\n");
                   5784:     } /* end j=0 */
1.249     brouard  5785:   } /* end j */
1.252     brouard  5786: 
1.253     brouard  5787:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5788:     for(i=1, jk=1; i <=nlstate; i++){
                   5789:       for(j=1; j <=nlstate+ndeath; j++){
                   5790:        if(j!=i){
                   5791:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5792:          printf("%1d%1d",i,j);
                   5793:          fprintf(ficparo,"%1d%1d",i,j);
                   5794:          for(k=1; k<=ncovmodel;k++){
                   5795:            /*    printf(" %lf",param[i][j][k]); */
                   5796:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5797:            p[jk]=pstart[jk];
                   5798:            printf(" %f ",pstart[jk]);
                   5799:            fprintf(ficparo," %f ",pstart[jk]);
                   5800:            jk++;
                   5801:          }
                   5802:          printf("\n");
                   5803:          fprintf(ficparo,"\n");
                   5804:        }
                   5805:       }
                   5806:     }
                   5807:   } /* end mle=-2 */
1.226     brouard  5808:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5809:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5810:   
1.226     brouard  5811:   fclose(ficresp);
                   5812:   fclose(ficresphtm);
                   5813:   fclose(ficresphtmfr);
1.283     brouard  5814:   free_vector(idq,1,nqfveff);
1.226     brouard  5815:   free_vector(meanq,1,nqfveff);
1.284     brouard  5816:   free_vector(stdq,1,nqfveff);
1.226     brouard  5817:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5818:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5819:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5820:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5821:   free_vector(pospropt,1,nlstate);
                   5822:   free_vector(posprop,1,nlstate);
1.251     brouard  5823:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5824:   free_vector(pp,1,nlstate);
                   5825:   /* End of freqsummary */
                   5826: }
1.126     brouard  5827: 
1.268     brouard  5828: /* Simple linear regression */
                   5829: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5830: 
                   5831:   /* y=a+bx regression */
                   5832:   double   sumx = 0.0;                        /* sum of x                      */
                   5833:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5834:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5835:   double   sumy = 0.0;                        /* sum of y                      */
                   5836:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5837:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5838:   double yhat;
                   5839:   
                   5840:   double denom=0;
                   5841:   int i;
                   5842:   int ne=*no;
                   5843:   
                   5844:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5845:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5846:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5847:       continue;
                   5848:     }
                   5849:     ne=ne+1;
                   5850:     sumx  += x[i];       
                   5851:     sumx2 += x[i]*x[i];  
                   5852:     sumxy += x[i] * y[i];
                   5853:     sumy  += y[i];      
                   5854:     sumy2 += y[i]*y[i]; 
                   5855:     denom = (ne * sumx2 - sumx*sumx);
                   5856:     /* 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); */
                   5857:   } 
                   5858:   
                   5859:   denom = (ne * sumx2 - sumx*sumx);
                   5860:   if (denom == 0) {
                   5861:     // vertical, slope m is infinity
                   5862:     *b = INFINITY;
                   5863:     *a = 0;
                   5864:     if (r) *r = 0;
                   5865:     return 1;
                   5866:   }
                   5867:   
                   5868:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5869:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5870:   if (r!=NULL) {
                   5871:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5872:       sqrt((sumx2 - sumx*sumx/ne) *
                   5873:           (sumy2 - sumy*sumy/ne));
                   5874:   }
                   5875:   *no=ne;
                   5876:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5877:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5878:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5879:       continue;
                   5880:     }
                   5881:     ne=ne+1;
                   5882:     yhat = y[i] - *a -*b* x[i];
                   5883:     sume2  += yhat * yhat ;       
                   5884:     
                   5885:     denom = (ne * sumx2 - sumx*sumx);
                   5886:     /* 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); */
                   5887:   } 
                   5888:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5889:   *sa= *sb * sqrt(sumx2/ne);
                   5890:   
                   5891:   return 0; 
                   5892: }
                   5893: 
1.126     brouard  5894: /************ Prevalence ********************/
1.227     brouard  5895: 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)
                   5896: {  
                   5897:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5898:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5899:      We still use firstpass and lastpass as another selection.
                   5900:   */
1.126     brouard  5901:  
1.227     brouard  5902:   int i, m, jk, j1, bool, z1,j, iv;
                   5903:   int mi; /* Effective wave */
                   5904:   int iage;
                   5905:   double agebegin, ageend;
                   5906: 
                   5907:   double **prop;
                   5908:   double posprop; 
                   5909:   double  y2; /* in fractional years */
                   5910:   int iagemin, iagemax;
                   5911:   int first; /** to stop verbosity which is redirected to log file */
                   5912: 
                   5913:   iagemin= (int) agemin;
                   5914:   iagemax= (int) agemax;
                   5915:   /*pp=vector(1,nlstate);*/
1.251     brouard  5916:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5917:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5918:   j1=0;
1.222     brouard  5919:   
1.227     brouard  5920:   /*j=cptcoveff;*/
                   5921:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5922:   
1.288     brouard  5923:   first=0;
1.335     brouard  5924:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5925:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5926:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5927:        prop[i][iage]=0.0;
                   5928:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5929:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5930:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5931:     
                   5932:     for (i=1; i<=imx; i++) { /* Each individual */
                   5933:       bool=1;
                   5934:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5935:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5936:        m=mw[mi][i];
                   5937:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5938:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5939:        for (z1=1; z1<=cptcoveff; z1++){
                   5940:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5941:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5942:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5943:              bool=0;
                   5944:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5945:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5946:              bool=0;
                   5947:            }
                   5948:        }
                   5949:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5950:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5951:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5952:          if(m >=firstpass && m <=lastpass){
                   5953:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5954:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5955:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5956:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5957:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5958:                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); 
                   5959:                exit(1);
                   5960:              }
                   5961:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5962:                /*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]]);*/
                   5963:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5964:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5965:              } /* end valid statuses */ 
                   5966:            } /* end selection of dates */
                   5967:          } /* end selection of waves */
                   5968:        } /* end bool */
                   5969:       } /* end wave */
                   5970:     } /* end individual */
                   5971:     for(i=iagemin; i <= iagemax+3; i++){  
                   5972:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5973:        posprop += prop[jk][i]; 
                   5974:       } 
                   5975:       
                   5976:       for(jk=1; jk <=nlstate ; jk++){      
                   5977:        if( i <=  iagemax){ 
                   5978:          if(posprop>=1.e-5){ 
                   5979:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5980:          } else{
1.288     brouard  5981:            if(!first){
                   5982:              first=1;
1.266     brouard  5983:              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]);
                   5984:            }else{
1.288     brouard  5985:              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  5986:            }
                   5987:          }
                   5988:        } 
                   5989:       }/* end jk */ 
                   5990:     }/* end i */ 
1.222     brouard  5991:      /*} *//* end i1 */
1.227     brouard  5992:   } /* end j1 */
1.222     brouard  5993:   
1.227     brouard  5994:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5995:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5996:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5997: }  /* End of prevalence */
1.126     brouard  5998: 
                   5999: /************* Waves Concatenation ***************/
                   6000: 
                   6001: 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)
                   6002: {
1.298     brouard  6003:   /* 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  6004:      Death is a valid wave (if date is known).
                   6005:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6006:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6007:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6008:   */
1.126     brouard  6009: 
1.224     brouard  6010:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6011:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6012:      double sum=0., jmean=0.;*/
1.224     brouard  6013:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6014:   int j, k=0,jk, ju, jl;
                   6015:   double sum=0.;
                   6016:   first=0;
1.214     brouard  6017:   firstwo=0;
1.217     brouard  6018:   firsthree=0;
1.218     brouard  6019:   firstfour=0;
1.164     brouard  6020:   jmin=100000;
1.126     brouard  6021:   jmax=-1;
                   6022:   jmean=0.;
1.224     brouard  6023: 
                   6024: /* Treating live states */
1.214     brouard  6025:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6026:     mi=0;  /* First valid wave */
1.227     brouard  6027:     mli=0; /* Last valid wave */
1.309     brouard  6028:     m=firstpass;  /* Loop on waves */
                   6029:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6030:       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 */
                   6031:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6032:       }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  6033:        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  6034:        mli=m;
1.224     brouard  6035:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6036:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6037:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6038:       }
1.309     brouard  6039:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6040: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6041:        break;
1.224     brouard  6042: #else
1.317     brouard  6043:        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  6044:          if(firsthree == 0){
1.302     brouard  6045:            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  6046:            firsthree=1;
1.317     brouard  6047:          }else if(firsthree >=1 && firsthree < 10){
                   6048:            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);
                   6049:            firsthree++;
                   6050:          }else if(firsthree == 10){
                   6051:            printf("Information, too many Information flags: no more reported to log either\n");
                   6052:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6053:            firsthree++;
                   6054:          }else{
                   6055:            firsthree++;
1.227     brouard  6056:          }
1.309     brouard  6057:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6058:          mli=m;
                   6059:        }
                   6060:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6061:          nbwarn++;
1.309     brouard  6062:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6063:            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);
                   6064:            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);
                   6065:          }
                   6066:          break;
                   6067:        }
                   6068:        break;
1.224     brouard  6069: #endif
1.227     brouard  6070:       }/* End m >= lastpass */
1.126     brouard  6071:     }/* end while */
1.224     brouard  6072: 
1.227     brouard  6073:     /* 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  6074:     /* After last pass */
1.224     brouard  6075: /* Treating death states */
1.214     brouard  6076:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6077:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6078:       /* } */
1.126     brouard  6079:       mi++;    /* Death is another wave */
                   6080:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6081:       /* Only death is a correct wave */
1.126     brouard  6082:       mw[mi][i]=m;
1.257     brouard  6083:     } /* else not in a death state */
1.224     brouard  6084: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6085:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6086:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6087:        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  6088:          nbwarn++;
                   6089:          if(firstfiv==0){
1.309     brouard  6090:            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  6091:            firstfiv=1;
                   6092:          }else{
1.309     brouard  6093:            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  6094:          }
1.309     brouard  6095:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6096:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6097:          nberr++;
                   6098:          if(firstwo==0){
1.309     brouard  6099:            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  6100:            firstwo=1;
                   6101:          }
1.309     brouard  6102:          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  6103:        }
1.257     brouard  6104:       }else{ /* if date of interview is unknown */
1.227     brouard  6105:        /* death is known but not confirmed by death status at any wave */
                   6106:        if(firstfour==0){
1.309     brouard  6107:          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  6108:          firstfour=1;
                   6109:        }
1.309     brouard  6110:        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  6111:       }
1.224     brouard  6112:     } /* end if date of death is known */
                   6113: #endif
1.309     brouard  6114:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6115:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6116:     if(mi==0){
                   6117:       nbwarn++;
                   6118:       if(first==0){
1.227     brouard  6119:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6120:        first=1;
1.126     brouard  6121:       }
                   6122:       if(first==1){
1.227     brouard  6123:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6124:       }
                   6125:     } /* end mi==0 */
                   6126:   } /* End individuals */
1.214     brouard  6127:   /* wav and mw are no more changed */
1.223     brouard  6128:        
1.317     brouard  6129:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6130:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6131: 
                   6132: 
1.126     brouard  6133:   for(i=1; i<=imx; i++){
                   6134:     for(mi=1; mi<wav[i];mi++){
                   6135:       if (stepm <=0)
1.227     brouard  6136:        dh[mi][i]=1;
1.126     brouard  6137:       else{
1.260     brouard  6138:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6139:          if (agedc[i] < 2*AGESUP) {
                   6140:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6141:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6142:            else if(j<0){
                   6143:              nberr++;
                   6144:              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]);
                   6145:              j=1; /* Temporary Dangerous patch */
                   6146:              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);
                   6147:              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]);
                   6148:              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);
                   6149:            }
                   6150:            k=k+1;
                   6151:            if (j >= jmax){
                   6152:              jmax=j;
                   6153:              ijmax=i;
                   6154:            }
                   6155:            if (j <= jmin){
                   6156:              jmin=j;
                   6157:              ijmin=i;
                   6158:            }
                   6159:            sum=sum+j;
                   6160:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6161:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6162:          }
                   6163:        }
                   6164:        else{
                   6165:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6166: /*       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  6167:                                        
1.227     brouard  6168:          k=k+1;
                   6169:          if (j >= jmax) {
                   6170:            jmax=j;
                   6171:            ijmax=i;
                   6172:          }
                   6173:          else if (j <= jmin){
                   6174:            jmin=j;
                   6175:            ijmin=i;
                   6176:          }
                   6177:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6178:          /*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]);*/
                   6179:          if(j<0){
                   6180:            nberr++;
                   6181:            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]);
                   6182:            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]);
                   6183:          }
                   6184:          sum=sum+j;
                   6185:        }
                   6186:        jk= j/stepm;
                   6187:        jl= j -jk*stepm;
                   6188:        ju= j -(jk+1)*stepm;
                   6189:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6190:          if(jl==0){
                   6191:            dh[mi][i]=jk;
                   6192:            bh[mi][i]=0;
                   6193:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6194:                  * to avoid the price of an extra matrix product in likelihood */
                   6195:            dh[mi][i]=jk+1;
                   6196:            bh[mi][i]=ju;
                   6197:          }
                   6198:        }else{
                   6199:          if(jl <= -ju){
                   6200:            dh[mi][i]=jk;
                   6201:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6202:                                 * is higher than the multiple of stepm and negative otherwise.
                   6203:                                 */
                   6204:          }
                   6205:          else{
                   6206:            dh[mi][i]=jk+1;
                   6207:            bh[mi][i]=ju;
                   6208:          }
                   6209:          if(dh[mi][i]==0){
                   6210:            dh[mi][i]=1; /* At least one step */
                   6211:            bh[mi][i]=ju; /* At least one step */
                   6212:            /*  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);*/
                   6213:          }
                   6214:        } /* end if mle */
1.126     brouard  6215:       }
                   6216:     } /* end wave */
                   6217:   }
                   6218:   jmean=sum/k;
                   6219:   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  6220:   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  6221: }
1.126     brouard  6222: 
                   6223: /*********** Tricode ****************************/
1.220     brouard  6224:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6225:  {
                   6226:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6227:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6228:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6229:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6230:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6231:     */
1.130     brouard  6232: 
1.242     brouard  6233:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6234:    int modmaxcovj=0; /* Modality max of covariates j */
                   6235:    int cptcode=0; /* Modality max of covariates j */
                   6236:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6237: 
                   6238: 
1.242     brouard  6239:    /* cptcoveff=0;  */
                   6240:    /* *cptcov=0; */
1.126     brouard  6241:  
1.242     brouard  6242:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6243:    for (k=1; k <= maxncov; k++)
                   6244:      for(j=1; j<=2; j++)
                   6245:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6246: 
1.242     brouard  6247:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6248:    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  6249:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6250:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.339     brouard  6251:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6252:        switch(Fixed[k]) {
                   6253:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6254:         modmaxcovj=0;
                   6255:         modmincovj=0;
1.242     brouard  6256:         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  6257:           /* 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  6258:           ij=(int)(covar[Tvar[k]][i]);
                   6259:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6260:            * If product of Vn*Vm, still boolean *:
                   6261:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6262:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6263:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6264:              modality of the nth covariate of individual i. */
                   6265:           if (ij > modmaxcovj)
                   6266:             modmaxcovj=ij; 
                   6267:           else if (ij < modmincovj) 
                   6268:             modmincovj=ij; 
1.287     brouard  6269:           if (ij <0 || ij >1 ){
1.311     brouard  6270:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6271:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6272:             fflush(ficlog);
                   6273:             exit(1);
1.287     brouard  6274:           }
                   6275:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6276:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6277:             exit(1);
                   6278:           }else
                   6279:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6280:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6281:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6282:           /* getting the maximum value of the modality of the covariate
                   6283:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6284:              female ies 1, then modmaxcovj=1.
                   6285:           */
                   6286:         } /* end for loop on individuals i */
                   6287:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6288:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6289:         cptcode=modmaxcovj;
                   6290:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6291:         /*for (i=0; i<=cptcode; i++) {*/
                   6292:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6293:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6294:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6295:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6296:             if( j != -1){
                   6297:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6298:                                  covariate for which somebody answered excluding 
                   6299:                                  undefined. Usually 2: 0 and 1. */
                   6300:             }
                   6301:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6302:                                     covariate for which somebody answered including 
                   6303:                                     undefined. Usually 3: -1, 0 and 1. */
                   6304:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6305:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6306:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6307:                        
1.242     brouard  6308:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6309:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6310:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6311:         /* modmincovj=3; modmaxcovj = 7; */
                   6312:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6313:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6314:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6315:         /* nbcode[Tvar[j]][ij]=k; */
                   6316:         /* nbcode[Tvar[j]][1]=0; */
                   6317:         /* nbcode[Tvar[j]][2]=1; */
                   6318:         /* nbcode[Tvar[j]][3]=2; */
                   6319:         /* To be continued (not working yet). */
                   6320:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6321: 
                   6322:         /* 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*/
                   6323:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6324:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6325:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6326:         /*, could be restored in the future */
                   6327:         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  6328:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6329:             break;
                   6330:           }
                   6331:           ij++;
1.287     brouard  6332:           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  6333:           cptcode = ij; /* New max modality for covar j */
                   6334:         } /* end of loop on modality i=-1 to 1 or more */
                   6335:         break;
                   6336:        case 1: /* Testing on varying covariate, could be simple and
                   6337:                * should look at waves or product of fixed *
                   6338:                * varying. No time to test -1, assuming 0 and 1 only */
                   6339:         ij=0;
                   6340:         for(i=0; i<=1;i++){
                   6341:           nbcode[Tvar[k]][++ij]=i;
                   6342:         }
                   6343:         break;
                   6344:        default:
                   6345:         break;
                   6346:        } /* end switch */
                   6347:      } /* end dummy test */
1.342     brouard  6348:      if(Dummy[k]==1 && Typevar[k] !=1 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6349:        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  6350:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6351:           printf("Error k=%d \n",k);
                   6352:           exit(1);
                   6353:         }
1.311     brouard  6354:         if(isnan(covar[Tvar[k]][i])){
                   6355:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6356:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6357:           fflush(ficlog);
                   6358:           exit(1);
                   6359:          }
                   6360:        }
1.335     brouard  6361:      } /* end Quanti */
1.287     brouard  6362:    } /* 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  6363:   
                   6364:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6365:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6366:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6367:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6368:      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 */ 
                   6369:      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 */
                   6370:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6371:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6372:   
                   6373:    ij=0;
                   6374:    /* 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  6375:    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 */
                   6376:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6377:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6378:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6379:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6380:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6381:        /* 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  6382:        /* If product not in single variable we don't print results */
                   6383:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6384:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6385:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6386:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6387:        /* ij            1    2                                            3  */  
                   6388:        /* Tvaraff[ij]=  4    3                                            1  */
                   6389:        /* Tmodelind[ij]=2    3                                            9  */
                   6390:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6391:        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*/
                   6392:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6393:        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 */
                   6394:        if(Fixed[k]!=0)
                   6395:         anyvaryingduminmodel=1;
                   6396:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6397:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6398:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6399:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6400:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6401:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6402:      } 
                   6403:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6404:    /* ij--; */
                   6405:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6406:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6407:                * because they can be excluded from the model and real
                   6408:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6409:    for(j=ij+1; j<= cptcovt; j++){
                   6410:      Tvaraff[j]=0;
                   6411:      Tmodelind[j]=0;
                   6412:    }
                   6413:    for(j=ntveff+1; j<= cptcovt; j++){
                   6414:      TmodelInvind[j]=0;
                   6415:    }
                   6416:    /* To be sorted */
                   6417:    ;
                   6418:  }
1.126     brouard  6419: 
1.145     brouard  6420: 
1.126     brouard  6421: /*********** Health Expectancies ****************/
                   6422: 
1.235     brouard  6423:  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  6424: 
                   6425: {
                   6426:   /* Health expectancies, no variances */
1.329     brouard  6427:   /* cij is the combination in the list of combination of dummy covariates */
                   6428:   /* strstart is a string of time at start of computing */
1.164     brouard  6429:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6430:   int nhstepma, nstepma; /* Decreasing with age */
                   6431:   double age, agelim, hf;
                   6432:   double ***p3mat;
                   6433:   double eip;
                   6434: 
1.238     brouard  6435:   /* pstamp(ficreseij); */
1.126     brouard  6436:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6437:   fprintf(ficreseij,"# Age");
                   6438:   for(i=1; i<=nlstate;i++){
                   6439:     for(j=1; j<=nlstate;j++){
                   6440:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6441:     }
                   6442:     fprintf(ficreseij," e%1d. ",i);
                   6443:   }
                   6444:   fprintf(ficreseij,"\n");
                   6445: 
                   6446:   
                   6447:   if(estepm < stepm){
                   6448:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6449:   }
                   6450:   else  hstepm=estepm;   
                   6451:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6452:    * This is mainly to measure the difference between two models: for example
                   6453:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6454:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6455:    * progression in between and thus overestimating or underestimating according
                   6456:    * to the curvature of the survival function. If, for the same date, we 
                   6457:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6458:    * to compare the new estimate of Life expectancy with the same linear 
                   6459:    * hypothesis. A more precise result, taking into account a more precise
                   6460:    * curvature will be obtained if estepm is as small as stepm. */
                   6461: 
                   6462:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6463:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6464:      nhstepm is the number of hstepm from age to agelim 
                   6465:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6466:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6467:      and note for a fixed period like estepm months */
                   6468:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6469:      survival function given by stepm (the optimization length). Unfortunately it
                   6470:      means that if the survival funtion is printed only each two years of age and if
                   6471:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6472:      results. So we changed our mind and took the option of the best precision.
                   6473:   */
                   6474:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6475: 
                   6476:   agelim=AGESUP;
                   6477:   /* If stepm=6 months */
                   6478:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6479:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6480:     
                   6481: /* nhstepm age range expressed in number of stepm */
                   6482:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6483:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6484:   /* if (stepm >= YEARM) hstepm=1;*/
                   6485:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6486:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6487: 
                   6488:   for (age=bage; age<=fage; age ++){ 
                   6489:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6490:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6491:     /* if (stepm >= YEARM) hstepm=1;*/
                   6492:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6493: 
                   6494:     /* If stepm=6 months */
                   6495:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6496:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6497:     /* 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  6498:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6499:     
                   6500:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6501:     
                   6502:     printf("%d|",(int)age);fflush(stdout);
                   6503:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6504:     
                   6505:     /* Computing expectancies */
                   6506:     for(i=1; i<=nlstate;i++)
                   6507:       for(j=1; j<=nlstate;j++)
                   6508:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6509:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6510:          
                   6511:          /* 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]);*/
                   6512: 
                   6513:        }
                   6514: 
                   6515:     fprintf(ficreseij,"%3.0f",age );
                   6516:     for(i=1; i<=nlstate;i++){
                   6517:       eip=0;
                   6518:       for(j=1; j<=nlstate;j++){
                   6519:        eip +=eij[i][j][(int)age];
                   6520:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6521:       }
                   6522:       fprintf(ficreseij,"%9.4f", eip );
                   6523:     }
                   6524:     fprintf(ficreseij,"\n");
                   6525:     
                   6526:   }
                   6527:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6528:   printf("\n");
                   6529:   fprintf(ficlog,"\n");
                   6530:   
                   6531: }
                   6532: 
1.235     brouard  6533:  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  6534: 
                   6535: {
                   6536:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6537:      to initial status i, ei. .
1.126     brouard  6538:   */
1.336     brouard  6539:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6540:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6541:   int nhstepma, nstepma; /* Decreasing with age */
                   6542:   double age, agelim, hf;
                   6543:   double ***p3matp, ***p3matm, ***varhe;
                   6544:   double **dnewm,**doldm;
                   6545:   double *xp, *xm;
                   6546:   double **gp, **gm;
                   6547:   double ***gradg, ***trgradg;
                   6548:   int theta;
                   6549: 
                   6550:   double eip, vip;
                   6551: 
                   6552:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6553:   xp=vector(1,npar);
                   6554:   xm=vector(1,npar);
                   6555:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6556:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6557:   
                   6558:   pstamp(ficresstdeij);
                   6559:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6560:   fprintf(ficresstdeij,"# Age");
                   6561:   for(i=1; i<=nlstate;i++){
                   6562:     for(j=1; j<=nlstate;j++)
                   6563:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6564:     fprintf(ficresstdeij," e%1d. ",i);
                   6565:   }
                   6566:   fprintf(ficresstdeij,"\n");
                   6567: 
                   6568:   pstamp(ficrescveij);
                   6569:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6570:   fprintf(ficrescveij,"# Age");
                   6571:   for(i=1; i<=nlstate;i++)
                   6572:     for(j=1; j<=nlstate;j++){
                   6573:       cptj= (j-1)*nlstate+i;
                   6574:       for(i2=1; i2<=nlstate;i2++)
                   6575:        for(j2=1; j2<=nlstate;j2++){
                   6576:          cptj2= (j2-1)*nlstate+i2;
                   6577:          if(cptj2 <= cptj)
                   6578:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6579:        }
                   6580:     }
                   6581:   fprintf(ficrescveij,"\n");
                   6582:   
                   6583:   if(estepm < stepm){
                   6584:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6585:   }
                   6586:   else  hstepm=estepm;   
                   6587:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6588:    * This is mainly to measure the difference between two models: for example
                   6589:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6590:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6591:    * progression in between and thus overestimating or underestimating according
                   6592:    * to the curvature of the survival function. If, for the same date, we 
                   6593:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6594:    * to compare the new estimate of Life expectancy with the same linear 
                   6595:    * hypothesis. A more precise result, taking into account a more precise
                   6596:    * curvature will be obtained if estepm is as small as stepm. */
                   6597: 
                   6598:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6599:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6600:      nhstepm is the number of hstepm from age to agelim 
                   6601:      nstepm is the number of stepm from age to agelin. 
                   6602:      Look at hpijx to understand the reason of that which relies in memory size
                   6603:      and note for a fixed period like estepm months */
                   6604:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6605:      survival function given by stepm (the optimization length). Unfortunately it
                   6606:      means that if the survival funtion is printed only each two years of age and if
                   6607:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6608:      results. So we changed our mind and took the option of the best precision.
                   6609:   */
                   6610:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6611: 
                   6612:   /* If stepm=6 months */
                   6613:   /* nhstepm age range expressed in number of stepm */
                   6614:   agelim=AGESUP;
                   6615:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6616:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6617:   /* if (stepm >= YEARM) hstepm=1;*/
                   6618:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6619:   
                   6620:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6621:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6622:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6623:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6624:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6625:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6626: 
                   6627:   for (age=bage; age<=fage; age ++){ 
                   6628:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6629:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6630:     /* if (stepm >= YEARM) hstepm=1;*/
                   6631:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6632:                
1.126     brouard  6633:     /* If stepm=6 months */
                   6634:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6635:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6636:     
                   6637:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6638:                
1.126     brouard  6639:     /* Computing  Variances of health expectancies */
                   6640:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6641:        decrease memory allocation */
                   6642:     for(theta=1; theta <=npar; theta++){
                   6643:       for(i=1; i<=npar; i++){ 
1.222     brouard  6644:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6645:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6646:       }
1.235     brouard  6647:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6648:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6649:                        
1.126     brouard  6650:       for(j=1; j<= nlstate; j++){
1.222     brouard  6651:        for(i=1; i<=nlstate; i++){
                   6652:          for(h=0; h<=nhstepm-1; h++){
                   6653:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6654:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6655:          }
                   6656:        }
1.126     brouard  6657:       }
1.218     brouard  6658:                        
1.126     brouard  6659:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6660:        for(h=0; h<=nhstepm-1; h++){
                   6661:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6662:        }
1.126     brouard  6663:     }/* End theta */
                   6664:     
                   6665:     
                   6666:     for(h=0; h<=nhstepm-1; h++)
                   6667:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6668:        for(theta=1; theta <=npar; theta++)
                   6669:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6670:     
1.218     brouard  6671:                
1.222     brouard  6672:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6673:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6674:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6675:                
1.222     brouard  6676:     printf("%d|",(int)age);fflush(stdout);
                   6677:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6678:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6679:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6680:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6681:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6682:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6683:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6684:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6685:       }
                   6686:     }
1.320     brouard  6687:     /* if((int)age ==50){ */
                   6688:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6689:     /* } */
1.126     brouard  6690:     /* Computing expectancies */
1.235     brouard  6691:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6692:     for(i=1; i<=nlstate;i++)
                   6693:       for(j=1; j<=nlstate;j++)
1.222     brouard  6694:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6695:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6696:                                        
1.222     brouard  6697:          /* 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  6698:                                        
1.222     brouard  6699:        }
1.269     brouard  6700: 
                   6701:     /* Standard deviation of expectancies ij */                
1.126     brouard  6702:     fprintf(ficresstdeij,"%3.0f",age );
                   6703:     for(i=1; i<=nlstate;i++){
                   6704:       eip=0.;
                   6705:       vip=0.;
                   6706:       for(j=1; j<=nlstate;j++){
1.222     brouard  6707:        eip += eij[i][j][(int)age];
                   6708:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6709:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6710:        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  6711:       }
                   6712:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6713:     }
                   6714:     fprintf(ficresstdeij,"\n");
1.218     brouard  6715:                
1.269     brouard  6716:     /* Variance of expectancies ij */          
1.126     brouard  6717:     fprintf(ficrescveij,"%3.0f",age );
                   6718:     for(i=1; i<=nlstate;i++)
                   6719:       for(j=1; j<=nlstate;j++){
1.222     brouard  6720:        cptj= (j-1)*nlstate+i;
                   6721:        for(i2=1; i2<=nlstate;i2++)
                   6722:          for(j2=1; j2<=nlstate;j2++){
                   6723:            cptj2= (j2-1)*nlstate+i2;
                   6724:            if(cptj2 <= cptj)
                   6725:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6726:          }
1.126     brouard  6727:       }
                   6728:     fprintf(ficrescveij,"\n");
1.218     brouard  6729:                
1.126     brouard  6730:   }
                   6731:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6732:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6733:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6734:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6735:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6736:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6737:   printf("\n");
                   6738:   fprintf(ficlog,"\n");
1.218     brouard  6739:        
1.126     brouard  6740:   free_vector(xm,1,npar);
                   6741:   free_vector(xp,1,npar);
                   6742:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6743:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6744:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6745: }
1.218     brouard  6746:  
1.126     brouard  6747: /************ Variance ******************/
1.235     brouard  6748:  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  6749:  {
1.279     brouard  6750:    /** Variance of health expectancies 
                   6751:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6752:     * double **newm;
                   6753:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6754:     */
1.218     brouard  6755:   
                   6756:    /* int movingaverage(); */
                   6757:    double **dnewm,**doldm;
                   6758:    double **dnewmp,**doldmp;
                   6759:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6760:    int first=0;
1.218     brouard  6761:    int k;
                   6762:    double *xp;
1.279     brouard  6763:    double **gp, **gm;  /**< for var eij */
                   6764:    double ***gradg, ***trgradg; /**< for var eij */
                   6765:    double **gradgp, **trgradgp; /**< for var p point j */
                   6766:    double *gpp, *gmp; /**< for var p point j */
                   6767:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6768:    double ***p3mat;
                   6769:    double age,agelim, hf;
                   6770:    /* double ***mobaverage; */
                   6771:    int theta;
                   6772:    char digit[4];
                   6773:    char digitp[25];
                   6774: 
                   6775:    char fileresprobmorprev[FILENAMELENGTH];
                   6776: 
                   6777:    if(popbased==1){
                   6778:      if(mobilav!=0)
                   6779:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6780:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6781:    }
                   6782:    else 
                   6783:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6784: 
1.218     brouard  6785:    /* if (mobilav!=0) { */
                   6786:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6787:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6788:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6789:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6790:    /*   } */
                   6791:    /* } */
                   6792: 
                   6793:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6794:    sprintf(digit,"%-d",ij);
                   6795:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6796:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6797:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6798:    strcat(fileresprobmorprev,fileresu);
                   6799:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6800:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6801:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6802:    }
                   6803:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6804:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6805:    pstamp(ficresprobmorprev);
                   6806:    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  6807:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6808: 
                   6809:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6810:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6811:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6812:    /* } */
                   6813:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344   ! brouard  6814:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  6815:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6816:    }
1.337     brouard  6817:    /* for(j=1;j<=cptcoveff;j++)  */
                   6818:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6819:    fprintf(ficresprobmorprev,"\n");
                   6820: 
1.218     brouard  6821:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6822:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6823:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6824:      for(i=1; i<=nlstate;i++)
                   6825:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6826:    }  
                   6827:    fprintf(ficresprobmorprev,"\n");
                   6828:   
                   6829:    fprintf(ficgp,"\n# Routine varevsij");
                   6830:    fprintf(ficgp,"\nunset title \n");
                   6831:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6832:    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");
                   6833:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6834: 
1.218     brouard  6835:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6836:    pstamp(ficresvij);
                   6837:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6838:    if(popbased==1)
                   6839:      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);
                   6840:    else
                   6841:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6842:    fprintf(ficresvij,"# Age");
                   6843:    for(i=1; i<=nlstate;i++)
                   6844:      for(j=1; j<=nlstate;j++)
                   6845:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6846:    fprintf(ficresvij,"\n");
                   6847: 
                   6848:    xp=vector(1,npar);
                   6849:    dnewm=matrix(1,nlstate,1,npar);
                   6850:    doldm=matrix(1,nlstate,1,nlstate);
                   6851:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6852:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6853: 
                   6854:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6855:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6856:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6857:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6858:   
1.218     brouard  6859:    if(estepm < stepm){
                   6860:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6861:    }
                   6862:    else  hstepm=estepm;   
                   6863:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6864:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6865:       nhstepm is the number of hstepm from age to agelim 
                   6866:       nstepm is the number of stepm from age to agelim. 
                   6867:       Look at function hpijx to understand why because of memory size limitations, 
                   6868:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6869:       survival function given by stepm (the optimization length). Unfortunately it
                   6870:       means that if the survival funtion is printed every two years of age and if
                   6871:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6872:       results. So we changed our mind and took the option of the best precision.
                   6873:    */
                   6874:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6875:    agelim = AGESUP;
                   6876:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6877:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6878:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6879:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6880:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6881:      gp=matrix(0,nhstepm,1,nlstate);
                   6882:      gm=matrix(0,nhstepm,1,nlstate);
                   6883:                
                   6884:                
                   6885:      for(theta=1; theta <=npar; theta++){
                   6886:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6887:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6888:        }
1.279     brouard  6889:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6890:        * returns into prlim .
1.288     brouard  6891:        */
1.242     brouard  6892:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6893: 
                   6894:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6895:        if (popbased==1) {
                   6896:         if(mobilav ==0){
                   6897:           for(i=1; i<=nlstate;i++)
                   6898:             prlim[i][i]=probs[(int)age][i][ij];
                   6899:         }else{ /* mobilav */ 
                   6900:           for(i=1; i<=nlstate;i++)
                   6901:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6902:         }
                   6903:        }
1.295     brouard  6904:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6905:        */                      
                   6906:        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  6907:        /**< 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  6908:        * at horizon h in state j including mortality.
                   6909:        */
1.218     brouard  6910:        for(j=1; j<= nlstate; j++){
                   6911:         for(h=0; h<=nhstepm; h++){
                   6912:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6913:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6914:         }
                   6915:        }
1.279     brouard  6916:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6917:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6918:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6919:        */
                   6920:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6921:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6922:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6923:        }
                   6924:        
                   6925:        /* Again with minus shift */
1.218     brouard  6926:                        
                   6927:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6928:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6929: 
1.242     brouard  6930:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6931:                        
                   6932:        if (popbased==1) {
                   6933:         if(mobilav ==0){
                   6934:           for(i=1; i<=nlstate;i++)
                   6935:             prlim[i][i]=probs[(int)age][i][ij];
                   6936:         }else{ /* mobilav */ 
                   6937:           for(i=1; i<=nlstate;i++)
                   6938:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6939:         }
                   6940:        }
                   6941:                        
1.235     brouard  6942:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6943:                        
                   6944:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6945:         for(h=0; h<=nhstepm; h++){
                   6946:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6947:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6948:         }
                   6949:        }
                   6950:        /* This for computing probability of death (h=1 means
                   6951:          computed over hstepm matrices product = hstepm*stepm months) 
                   6952:          as a weighted average of prlim.
                   6953:        */
                   6954:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6955:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6956:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6957:        }    
1.279     brouard  6958:        /* end shifting computations */
                   6959: 
                   6960:        /**< Computing gradient matrix at horizon h 
                   6961:        */
1.218     brouard  6962:        for(j=1; j<= nlstate; j++) /* vareij */
                   6963:         for(h=0; h<=nhstepm; h++){
                   6964:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6965:         }
1.279     brouard  6966:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6967:        */
                   6968:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6969:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6970:        }
                   6971:                        
                   6972:      } /* End theta */
1.279     brouard  6973:      
                   6974:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6975:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6976:                
                   6977:      for(h=0; h<=nhstepm; h++) /* veij */
                   6978:        for(j=1; j<=nlstate;j++)
                   6979:         for(theta=1; theta <=npar; theta++)
                   6980:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6981:                
                   6982:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6983:        for(theta=1; theta <=npar; theta++)
                   6984:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6985:      /**< as well as its transposed matrix 
                   6986:       */               
1.218     brouard  6987:                
                   6988:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6989:      for(i=1;i<=nlstate;i++)
                   6990:        for(j=1;j<=nlstate;j++)
                   6991:         vareij[i][j][(int)age] =0.;
1.279     brouard  6992: 
                   6993:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6994:       * and k (nhstepm) formula 15 of article
                   6995:       * Lievre-Brouard-Heathcote
                   6996:       */
                   6997:      
1.218     brouard  6998:      for(h=0;h<=nhstepm;h++){
                   6999:        for(k=0;k<=nhstepm;k++){
                   7000:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7001:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7002:         for(i=1;i<=nlstate;i++)
                   7003:           for(j=1;j<=nlstate;j++)
                   7004:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7005:        }
                   7006:      }
                   7007:                
1.279     brouard  7008:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7009:       * p.j overall mortality formula 49 but computed directly because
                   7010:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7011:       * wix is independent of theta.
                   7012:       */
1.218     brouard  7013:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7014:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7015:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7016:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7017:         varppt[j][i]=doldmp[j][i];
                   7018:      /* end ppptj */
                   7019:      /*  x centered again */
                   7020:                
1.242     brouard  7021:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7022:                
                   7023:      if (popbased==1) {
                   7024:        if(mobilav ==0){
                   7025:         for(i=1; i<=nlstate;i++)
                   7026:           prlim[i][i]=probs[(int)age][i][ij];
                   7027:        }else{ /* mobilav */ 
                   7028:         for(i=1; i<=nlstate;i++)
                   7029:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7030:        }
                   7031:      }
                   7032:                
                   7033:      /* This for computing probability of death (h=1 means
                   7034:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7035:        as a weighted average of prlim.
                   7036:      */
1.235     brouard  7037:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7038:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7039:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7040:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7041:      }    
                   7042:      /* end probability of death */
                   7043:                
                   7044:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7045:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7046:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7047:        for(i=1; i<=nlstate;i++){
                   7048:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7049:        }
                   7050:      } 
                   7051:      fprintf(ficresprobmorprev,"\n");
                   7052:                
                   7053:      fprintf(ficresvij,"%.0f ",age );
                   7054:      for(i=1; i<=nlstate;i++)
                   7055:        for(j=1; j<=nlstate;j++){
                   7056:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7057:        }
                   7058:      fprintf(ficresvij,"\n");
                   7059:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7060:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7061:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7062:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7063:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7064:    } /* End age */
                   7065:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7066:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7067:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7068:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7069:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7070:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7071:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7072:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7073:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7074:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7075:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7076:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7077:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7078:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7079:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7080:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7081:    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);
                   7082:    /*  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  7083:     */
1.218     brouard  7084:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7085:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7086: 
1.218     brouard  7087:    free_vector(xp,1,npar);
                   7088:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7089:    free_matrix(dnewm,1,nlstate,1,npar);
                   7090:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7091:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7092:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7093:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7094:    fclose(ficresprobmorprev);
                   7095:    fflush(ficgp);
                   7096:    fflush(fichtm); 
                   7097:  }  /* end varevsij */
1.126     brouard  7098: 
                   7099: /************ Variance of prevlim ******************/
1.269     brouard  7100:  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  7101: {
1.205     brouard  7102:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7103:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7104: 
1.268     brouard  7105:   double **dnewmpar,**doldm;
1.126     brouard  7106:   int i, j, nhstepm, hstepm;
                   7107:   double *xp;
                   7108:   double *gp, *gm;
                   7109:   double **gradg, **trgradg;
1.208     brouard  7110:   double **mgm, **mgp;
1.126     brouard  7111:   double age,agelim;
                   7112:   int theta;
                   7113:   
                   7114:   pstamp(ficresvpl);
1.288     brouard  7115:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7116:   fprintf(ficresvpl,"# Age ");
                   7117:   if(nresult >=1)
                   7118:     fprintf(ficresvpl," Result# ");
1.126     brouard  7119:   for(i=1; i<=nlstate;i++)
                   7120:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7121:   fprintf(ficresvpl,"\n");
                   7122: 
                   7123:   xp=vector(1,npar);
1.268     brouard  7124:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7125:   doldm=matrix(1,nlstate,1,nlstate);
                   7126:   
                   7127:   hstepm=1*YEARM; /* Every year of age */
                   7128:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7129:   agelim = AGESUP;
                   7130:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7131:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7132:     if (stepm >= YEARM) hstepm=1;
                   7133:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7134:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7135:     mgp=matrix(1,npar,1,nlstate);
                   7136:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7137:     gp=vector(1,nlstate);
                   7138:     gm=vector(1,nlstate);
                   7139: 
                   7140:     for(theta=1; theta <=npar; theta++){
                   7141:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7142:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7143:       }
1.288     brouard  7144:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7145:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7146:       /* else */
                   7147:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7148:       for(i=1;i<=nlstate;i++){
1.126     brouard  7149:        gp[i] = prlim[i][i];
1.208     brouard  7150:        mgp[theta][i] = prlim[i][i];
                   7151:       }
1.126     brouard  7152:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7153:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7154:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7155:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7156:       /* else */
                   7157:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7158:       for(i=1;i<=nlstate;i++){
1.126     brouard  7159:        gm[i] = prlim[i][i];
1.208     brouard  7160:        mgm[theta][i] = prlim[i][i];
                   7161:       }
1.126     brouard  7162:       for(i=1;i<=nlstate;i++)
                   7163:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7164:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7165:     } /* End theta */
                   7166: 
                   7167:     trgradg =matrix(1,nlstate,1,npar);
                   7168: 
                   7169:     for(j=1; j<=nlstate;j++)
                   7170:       for(theta=1; theta <=npar; theta++)
                   7171:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7172:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7173:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7174:     /*   for(j=1; j<=nlstate;j++){ */
                   7175:     /*         printf(" %d ",j); */
                   7176:     /*         for(theta=1; theta <=npar; theta++) */
                   7177:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7178:     /*         printf("\n "); */
                   7179:     /*   } */
                   7180:     /* } */
                   7181:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7182:     /*   printf("\n gradg %d ",(int)age); */
                   7183:     /*   for(j=1; j<=nlstate;j++){ */
                   7184:     /*         printf("%d ",j); */
                   7185:     /*         for(theta=1; theta <=npar; theta++) */
                   7186:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7187:     /*         printf("\n "); */
                   7188:     /*   } */
                   7189:     /* } */
1.126     brouard  7190: 
                   7191:     for(i=1;i<=nlstate;i++)
                   7192:       varpl[i][(int)age] =0.;
1.209     brouard  7193:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7194:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7195:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7196:     }else{
1.268     brouard  7197:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7198:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7199:     }
1.126     brouard  7200:     for(i=1;i<=nlstate;i++)
                   7201:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7202: 
                   7203:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7204:     if(nresult >=1)
                   7205:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7206:     for(i=1; i<=nlstate;i++){
1.126     brouard  7207:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7208:       /* for(j=1;j<=nlstate;j++) */
                   7209:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7210:     }
1.126     brouard  7211:     fprintf(ficresvpl,"\n");
                   7212:     free_vector(gp,1,nlstate);
                   7213:     free_vector(gm,1,nlstate);
1.208     brouard  7214:     free_matrix(mgm,1,npar,1,nlstate);
                   7215:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7216:     free_matrix(gradg,1,npar,1,nlstate);
                   7217:     free_matrix(trgradg,1,nlstate,1,npar);
                   7218:   } /* End age */
                   7219: 
                   7220:   free_vector(xp,1,npar);
                   7221:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7222:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7223: 
                   7224: }
                   7225: 
                   7226: 
                   7227: /************ Variance of backprevalence limit ******************/
1.269     brouard  7228:  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  7229: {
                   7230:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7231:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7232: 
                   7233:   double **dnewmpar,**doldm;
                   7234:   int i, j, nhstepm, hstepm;
                   7235:   double *xp;
                   7236:   double *gp, *gm;
                   7237:   double **gradg, **trgradg;
                   7238:   double **mgm, **mgp;
                   7239:   double age,agelim;
                   7240:   int theta;
                   7241:   
                   7242:   pstamp(ficresvbl);
                   7243:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7244:   fprintf(ficresvbl,"# Age ");
                   7245:   if(nresult >=1)
                   7246:     fprintf(ficresvbl," Result# ");
                   7247:   for(i=1; i<=nlstate;i++)
                   7248:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7249:   fprintf(ficresvbl,"\n");
                   7250: 
                   7251:   xp=vector(1,npar);
                   7252:   dnewmpar=matrix(1,nlstate,1,npar);
                   7253:   doldm=matrix(1,nlstate,1,nlstate);
                   7254:   
                   7255:   hstepm=1*YEARM; /* Every year of age */
                   7256:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7257:   agelim = AGEINF;
                   7258:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7259:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7260:     if (stepm >= YEARM) hstepm=1;
                   7261:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7262:     gradg=matrix(1,npar,1,nlstate);
                   7263:     mgp=matrix(1,npar,1,nlstate);
                   7264:     mgm=matrix(1,npar,1,nlstate);
                   7265:     gp=vector(1,nlstate);
                   7266:     gm=vector(1,nlstate);
                   7267: 
                   7268:     for(theta=1; theta <=npar; theta++){
                   7269:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7270:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7271:       }
                   7272:       if(mobilavproj > 0 )
                   7273:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7274:       else
                   7275:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7276:       for(i=1;i<=nlstate;i++){
                   7277:        gp[i] = bprlim[i][i];
                   7278:        mgp[theta][i] = bprlim[i][i];
                   7279:       }
                   7280:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7281:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7282:        if(mobilavproj > 0 )
                   7283:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7284:        else
                   7285:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7286:       for(i=1;i<=nlstate;i++){
                   7287:        gm[i] = bprlim[i][i];
                   7288:        mgm[theta][i] = bprlim[i][i];
                   7289:       }
                   7290:       for(i=1;i<=nlstate;i++)
                   7291:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7292:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7293:     } /* End theta */
                   7294: 
                   7295:     trgradg =matrix(1,nlstate,1,npar);
                   7296: 
                   7297:     for(j=1; j<=nlstate;j++)
                   7298:       for(theta=1; theta <=npar; theta++)
                   7299:        trgradg[j][theta]=gradg[theta][j];
                   7300:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7301:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7302:     /*   for(j=1; j<=nlstate;j++){ */
                   7303:     /*         printf(" %d ",j); */
                   7304:     /*         for(theta=1; theta <=npar; theta++) */
                   7305:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7306:     /*         printf("\n "); */
                   7307:     /*   } */
                   7308:     /* } */
                   7309:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7310:     /*   printf("\n gradg %d ",(int)age); */
                   7311:     /*   for(j=1; j<=nlstate;j++){ */
                   7312:     /*         printf("%d ",j); */
                   7313:     /*         for(theta=1; theta <=npar; theta++) */
                   7314:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7315:     /*         printf("\n "); */
                   7316:     /*   } */
                   7317:     /* } */
                   7318: 
                   7319:     for(i=1;i<=nlstate;i++)
                   7320:       varbpl[i][(int)age] =0.;
                   7321:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7322:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7323:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7324:     }else{
                   7325:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7326:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7327:     }
                   7328:     for(i=1;i<=nlstate;i++)
                   7329:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7330: 
                   7331:     fprintf(ficresvbl,"%.0f ",age );
                   7332:     if(nresult >=1)
                   7333:       fprintf(ficresvbl,"%d ",nres );
                   7334:     for(i=1; i<=nlstate;i++)
                   7335:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7336:     fprintf(ficresvbl,"\n");
                   7337:     free_vector(gp,1,nlstate);
                   7338:     free_vector(gm,1,nlstate);
                   7339:     free_matrix(mgm,1,npar,1,nlstate);
                   7340:     free_matrix(mgp,1,npar,1,nlstate);
                   7341:     free_matrix(gradg,1,npar,1,nlstate);
                   7342:     free_matrix(trgradg,1,nlstate,1,npar);
                   7343:   } /* End age */
                   7344: 
                   7345:   free_vector(xp,1,npar);
                   7346:   free_matrix(doldm,1,nlstate,1,npar);
                   7347:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7348: 
                   7349: }
                   7350: 
                   7351: /************ Variance of one-step probabilities  ******************/
                   7352: 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  7353:  {
                   7354:    int i, j=0,  k1, l1, tj;
                   7355:    int k2, l2, j1,  z1;
                   7356:    int k=0, l;
                   7357:    int first=1, first1, first2;
1.326     brouard  7358:    int nres=0; /* New */
1.222     brouard  7359:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7360:    double **dnewm,**doldm;
                   7361:    double *xp;
                   7362:    double *gp, *gm;
                   7363:    double **gradg, **trgradg;
                   7364:    double **mu;
                   7365:    double age, cov[NCOVMAX+1];
                   7366:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7367:    int theta;
                   7368:    char fileresprob[FILENAMELENGTH];
                   7369:    char fileresprobcov[FILENAMELENGTH];
                   7370:    char fileresprobcor[FILENAMELENGTH];
                   7371:    double ***varpij;
                   7372: 
                   7373:    strcpy(fileresprob,"PROB_"); 
                   7374:    strcat(fileresprob,fileres);
                   7375:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7376:      printf("Problem with resultfile: %s\n", fileresprob);
                   7377:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7378:    }
                   7379:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7380:    strcat(fileresprobcov,fileresu);
                   7381:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7382:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7383:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7384:    }
                   7385:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7386:    strcat(fileresprobcor,fileresu);
                   7387:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7388:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7389:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7390:    }
                   7391:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7392:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7393:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7394:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7395:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7396:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7397:    pstamp(ficresprob);
                   7398:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7399:    fprintf(ficresprob,"# Age");
                   7400:    pstamp(ficresprobcov);
                   7401:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7402:    fprintf(ficresprobcov,"# Age");
                   7403:    pstamp(ficresprobcor);
                   7404:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7405:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7406: 
                   7407: 
1.222     brouard  7408:    for(i=1; i<=nlstate;i++)
                   7409:      for(j=1; j<=(nlstate+ndeath);j++){
                   7410:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7411:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7412:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7413:      }  
                   7414:    /* fprintf(ficresprob,"\n");
                   7415:       fprintf(ficresprobcov,"\n");
                   7416:       fprintf(ficresprobcor,"\n");
                   7417:    */
                   7418:    xp=vector(1,npar);
                   7419:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7420:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7421:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7422:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7423:    first=1;
                   7424:    fprintf(ficgp,"\n# Routine varprob");
                   7425:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7426:    fprintf(fichtm,"\n");
                   7427: 
1.288     brouard  7428:    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  7429:    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);
                   7430:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7431: and drawn. It helps understanding how is the covariance between two incidences.\
                   7432:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7433:    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  7434: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7435: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7436: standard deviations wide on each axis. <br>\
                   7437:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7438:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7439: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7440: 
1.222     brouard  7441:    cov[1]=1;
                   7442:    /* tj=cptcoveff; */
1.225     brouard  7443:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7444:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7445:    j1=0;
1.332     brouard  7446: 
                   7447:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7448:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7449:      /* 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  7450:      if(tj != 1 && TKresult[nres]!= j1)
                   7451:        continue;
                   7452: 
                   7453:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7454:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7455:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7456:      if  (cptcovn>0) {
1.334     brouard  7457:        fprintf(ficresprob, "\n#********** Variable ");
                   7458:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7459:        fprintf(ficgp, "\n#********** Variable ");
                   7460:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7461:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7462: 
                   7463:        /* Including quantitative variables of the resultline to be done */
                   7464:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7465:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7466:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7467:         /* 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  7468:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7469:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7470:             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  */
                   7471:             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  */
                   7472:             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  */
                   7473:             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  */
                   7474:             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  */
                   7475:             fprintf(ficresprob,"fixed ");
                   7476:             fprintf(ficresprobcov,"fixed ");
                   7477:             fprintf(ficgp,"fixed ");
                   7478:             fprintf(fichtmcov,"fixed ");
                   7479:             fprintf(ficresprobcor,"fixed ");
                   7480:           }else{
                   7481:             fprintf(ficresprob,"varyi ");
                   7482:             fprintf(ficresprobcov,"varyi ");
                   7483:             fprintf(ficgp,"varyi ");
                   7484:             fprintf(fichtmcov,"varyi ");
                   7485:             fprintf(ficresprobcor,"varyi ");
                   7486:           }
                   7487:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7488:           /* For each selected (single) quantitative value */
1.337     brouard  7489:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7490:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7491:             fprintf(ficresprob,"fixed ");
                   7492:             fprintf(ficresprobcov,"fixed ");
                   7493:             fprintf(ficgp,"fixed ");
                   7494:             fprintf(fichtmcov,"fixed ");
                   7495:             fprintf(ficresprobcor,"fixed ");
                   7496:           }else{
                   7497:             fprintf(ficresprob,"varyi ");
                   7498:             fprintf(ficresprobcov,"varyi ");
                   7499:             fprintf(ficgp,"varyi ");
                   7500:             fprintf(fichtmcov,"varyi ");
                   7501:             fprintf(ficresprobcor,"varyi ");
                   7502:           }
                   7503:         }else{
                   7504:           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 */
                   7505:           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 */
                   7506:           exit(1);
                   7507:         }
                   7508:        } /* End loop on variable of this resultline */
                   7509:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7510:        fprintf(ficresprob, "**********\n#\n");
                   7511:        fprintf(ficresprobcov, "**********\n#\n");
                   7512:        fprintf(ficgp, "**********\n#\n");
                   7513:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7514:        fprintf(ficresprobcor, "**********\n#");    
                   7515:        if(invalidvarcomb[j1]){
                   7516:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7517:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7518:         continue;
                   7519:        }
                   7520:      }
                   7521:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7522:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7523:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7524:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7525:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7526:        cov[2]=age;
                   7527:        if(nagesqr==1)
                   7528:         cov[3]= age*age;
1.334     brouard  7529:        /* New code end of combination but for each resultline */
                   7530:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7531:         if(Typevar[k1]==1){ /* A product with age */
                   7532:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7533:         }else{
1.334     brouard  7534:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7535:         }
1.334     brouard  7536:        }/* End of loop on model equation */
                   7537: /* Old code */
                   7538:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7539:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7540:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7541:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7542:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7543:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7544:        /*                                                                  * 1  1 1 1 1 */
                   7545:        /*                                                                  * 2  2 1 1 1 */
                   7546:        /*                                                                  * 3  1 2 1 1 */
                   7547:        /*                                                                  *\/ */
                   7548:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7549:        /* } */
                   7550:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7551:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7552:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7553:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7554:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7555:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7556:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7557:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7558:        /*         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]); */
                   7559:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7560:        /*         /\* exit(1); *\/ */
                   7561:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7562:        /*       } */
                   7563:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7564:        /* } */
                   7565:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7566:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7567:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7568:        /*           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]])]; */
                   7569:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7570:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7571:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7572:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7573:        /*         } */
                   7574:        /*       }else{ */
                   7575:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7576:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7577:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7578:        /*         }else{ */
                   7579:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7580:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7581:        /*         } */
                   7582:        /*       } */
                   7583:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7584:        /* } */                 
1.326     brouard  7585: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7586:        for(theta=1; theta <=npar; theta++){
                   7587:         for(i=1; i<=npar; i++)
                   7588:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7589:                                
1.222     brouard  7590:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7591:                                
1.222     brouard  7592:         k=0;
                   7593:         for(i=1; i<= (nlstate); i++){
                   7594:           for(j=1; j<=(nlstate+ndeath);j++){
                   7595:             k=k+1;
                   7596:             gp[k]=pmmij[i][j];
                   7597:           }
                   7598:         }
1.220     brouard  7599:                                
1.222     brouard  7600:         for(i=1; i<=npar; i++)
                   7601:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7602:                                
1.222     brouard  7603:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7604:         k=0;
                   7605:         for(i=1; i<=(nlstate); i++){
                   7606:           for(j=1; j<=(nlstate+ndeath);j++){
                   7607:             k=k+1;
                   7608:             gm[k]=pmmij[i][j];
                   7609:           }
                   7610:         }
1.220     brouard  7611:                                
1.222     brouard  7612:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7613:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7614:        }
1.126     brouard  7615: 
1.222     brouard  7616:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7617:         for(theta=1; theta <=npar; theta++)
                   7618:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7619:                        
1.222     brouard  7620:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7621:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7622:                        
1.222     brouard  7623:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7624:                        
1.222     brouard  7625:        k=0;
                   7626:        for(i=1; i<=(nlstate); i++){
                   7627:         for(j=1; j<=(nlstate+ndeath);j++){
                   7628:           k=k+1;
                   7629:           mu[k][(int) age]=pmmij[i][j];
                   7630:         }
                   7631:        }
                   7632:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7633:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7634:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7635:                        
1.222     brouard  7636:        /*printf("\n%d ",(int)age);
                   7637:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7638:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7639:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7640:         }*/
1.220     brouard  7641:                        
1.222     brouard  7642:        fprintf(ficresprob,"\n%d ",(int)age);
                   7643:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7644:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7645:                        
1.222     brouard  7646:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7647:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7648:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7649:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7650:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7651:        }
                   7652:        i=0;
                   7653:        for (k=1; k<=(nlstate);k++){
                   7654:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7655:           i++;
                   7656:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7657:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7658:           for (j=1; j<=i;j++){
                   7659:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7660:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7661:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7662:           }
                   7663:         }
                   7664:        }/* end of loop for state */
                   7665:      } /* end of loop for age */
                   7666:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7667:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7668:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7669:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7670:     
                   7671:      /* Confidence intervalle of pij  */
                   7672:      /*
                   7673:        fprintf(ficgp,"\nunset parametric;unset label");
                   7674:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7675:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7676:        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);
                   7677:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7678:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7679:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7680:      */
                   7681:                
                   7682:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7683:      first1=1;first2=2;
                   7684:      for (k2=1; k2<=(nlstate);k2++){
                   7685:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7686:         if(l2==k2) continue;
                   7687:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7688:         for (k1=1; k1<=(nlstate);k1++){
                   7689:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7690:             if(l1==k1) continue;
                   7691:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7692:             if(i<=j) continue;
                   7693:             for (age=bage; age<=fage; age ++){ 
                   7694:               if ((int)age %5==0){
                   7695:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7696:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7697:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7698:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7699:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7700:                 c12=cv12/sqrt(v1*v2);
                   7701:                 /* Computing eigen value of matrix of covariance */
                   7702:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7703:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7704:                 if ((lc2 <0) || (lc1 <0) ){
                   7705:                   if(first2==1){
                   7706:                     first1=0;
                   7707:                     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);
                   7708:                   }
                   7709:                   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);
                   7710:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7711:                   /* lc2=fabs(lc2); */
                   7712:                 }
1.220     brouard  7713:                                                                
1.222     brouard  7714:                 /* Eigen vectors */
1.280     brouard  7715:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7716:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7717:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7718:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7719:                 }else
                   7720:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7721:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7722:                 v21=(lc1-v1)/cv12*v11;
                   7723:                 v12=-v21;
                   7724:                 v22=v11;
                   7725:                 tnalp=v21/v11;
                   7726:                 if(first1==1){
                   7727:                   first1=0;
                   7728:                   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);
                   7729:                 }
                   7730:                 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);
                   7731:                 /*printf(fignu*/
                   7732:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7733:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7734:                 if(first==1){
                   7735:                   first=0;
                   7736:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7737:                   fprintf(ficgp,"\nset parametric;unset label");
                   7738:                   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);
                   7739:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7740:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7741:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7742: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7743:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7744:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7745:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7746:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7747:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7748:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7749:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7750:                   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  7751:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7752:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7753:                 }else{
                   7754:                   first=0;
                   7755:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7756:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7757:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7758:                   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  7759:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7760:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7761:                 }/* if first */
                   7762:               } /* age mod 5 */
                   7763:             } /* end loop age */
                   7764:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7765:             first=1;
                   7766:           } /*l12 */
                   7767:         } /* k12 */
                   7768:        } /*l1 */
                   7769:      }/* k1 */
1.332     brouard  7770:    }  /* loop on combination of covariates j1 */
1.326     brouard  7771:    } /* loop on nres */
1.222     brouard  7772:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7773:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7774:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7775:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7776:    free_vector(xp,1,npar);
                   7777:    fclose(ficresprob);
                   7778:    fclose(ficresprobcov);
                   7779:    fclose(ficresprobcor);
                   7780:    fflush(ficgp);
                   7781:    fflush(fichtmcov);
                   7782:  }
1.126     brouard  7783: 
                   7784: 
                   7785: /******************* Printing html file ***********/
1.201     brouard  7786: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7787:                  int lastpass, int stepm, int weightopt, char model[],\
                   7788:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7789:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7790:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7791:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7792:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7793:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7794:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7795:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7796: </ul>");
1.319     brouard  7797: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7798: /* </ul>", model); */
1.214     brouard  7799:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7800:    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",
                   7801:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7802:    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  7803:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7804:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7805:    fprintf(fichtm,"\
                   7806:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7807:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7808:    fprintf(fichtm,"\
1.217     brouard  7809:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7810:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7811:    fprintf(fichtm,"\
1.288     brouard  7812:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7813:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7814:    fprintf(fichtm,"\
1.288     brouard  7815:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7816:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7817:    fprintf(fichtm,"\
1.211     brouard  7818:  - (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  7819:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7820:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7821:    if(prevfcast==1){
                   7822:      fprintf(fichtm,"\
                   7823:  - Prevalence projections by age and states:                           \
1.201     brouard  7824:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7825:    }
1.126     brouard  7826: 
                   7827: 
1.225     brouard  7828:    m=pow(2,cptcoveff);
1.222     brouard  7829:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7830: 
1.317     brouard  7831:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7832: 
                   7833:    jj1=0;
                   7834: 
                   7835:    fprintf(fichtm," \n<ul>");
1.337     brouard  7836:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7837:      /* k1=nres; */
1.338     brouard  7838:      k1=TKresult[nres];
                   7839:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7840:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7841:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7842:    /*     continue; */
1.264     brouard  7843:      jj1++;
                   7844:      if (cptcovn > 0) {
                   7845:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7846:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7847:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7848:        }
1.337     brouard  7849:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7850:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7851:        /* } */
                   7852:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7853:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7854:        /* } */
1.264     brouard  7855:        fprintf(fichtm,"\">");
                   7856:        
                   7857:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7858:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7859:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7860:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7861:        }
1.337     brouard  7862:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7863:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7864:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7865:        /* } */
                   7866:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7867:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7868:        /* } */
1.264     brouard  7869:        if(invalidvarcomb[k1]){
                   7870:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7871:         continue;
                   7872:        }
                   7873:        fprintf(fichtm,"</a></li>");
                   7874:      } /* cptcovn >0 */
                   7875:    }
1.317     brouard  7876:    fprintf(fichtm," \n</ul>");
1.264     brouard  7877: 
1.222     brouard  7878:    jj1=0;
1.237     brouard  7879: 
1.337     brouard  7880:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7881:      /* k1=nres; */
1.338     brouard  7882:      k1=TKresult[nres];
                   7883:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7884:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7885:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7886:    /*     continue; */
1.220     brouard  7887: 
1.222     brouard  7888:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7889:      jj1++;
                   7890:      if (cptcovn > 0) {
1.264     brouard  7891:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7892:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7893:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7894:        }
1.337     brouard  7895:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7896:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7897:        /* } */
1.264     brouard  7898:        fprintf(fichtm,"\"</a>");
                   7899:  
1.222     brouard  7900:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7901:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7902:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7903:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7904:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7905:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7906:        }
1.230     brouard  7907:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7908:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7909:        if(invalidvarcomb[k1]){
                   7910:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7911:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7912:         continue;
                   7913:        }
                   7914:      }
                   7915:      /* aij, bij */
1.259     brouard  7916:      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  7917: <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  7918:      /* Pij */
1.241     brouard  7919:      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> \
                   7920: <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  7921:      /* Quasi-incidences */
                   7922:      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  7923:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7924:  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  7925: 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> \
                   7926: <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  7927:      /* Survival functions (period) in state j */
                   7928:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7929:        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);
                   7930:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7931:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7932:      }
                   7933:      /* State specific survival functions (period) */
                   7934:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7935:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7936:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7937:  <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);
                   7938:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7939:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7940:      }
1.288     brouard  7941:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7942:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7943:        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  7944:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7945:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7946:      }
1.296     brouard  7947:      if(prevbcast==1){
1.288     brouard  7948:        /* Backward prevalence in each health state */
1.222     brouard  7949:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7950:         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);
                   7951:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7952:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7953:        }
1.217     brouard  7954:      }
1.222     brouard  7955:      if(prevfcast==1){
1.288     brouard  7956:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7957:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7958:         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);
                   7959:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7960:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7961:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7962:        }
                   7963:      }
1.296     brouard  7964:      if(prevbcast==1){
1.268     brouard  7965:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7966:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7967:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7968:  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 \
                   7969:  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  7970: 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);
                   7971:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7972:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7973:        }
                   7974:      }
1.220     brouard  7975:         
1.222     brouard  7976:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7977:        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);
                   7978:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7979:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7980:      }
                   7981:      /* } /\* end i1 *\/ */
1.337     brouard  7982:    }/* End k1=nres */
1.222     brouard  7983:    fprintf(fichtm,"</ul>");
1.126     brouard  7984: 
1.222     brouard  7985:    fprintf(fichtm,"\
1.126     brouard  7986: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7987:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7988:  - 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  7989: But because parameters are usually highly correlated (a higher incidence of disability \
                   7990: and a higher incidence of recovery can give very close observed transition) it might \
                   7991: be very useful to look not only at linear confidence intervals estimated from the \
                   7992: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7993: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7994: covariance matrix of the one-step probabilities. \
                   7995: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7996: 
1.222     brouard  7997:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7998:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7999:    fprintf(fichtm,"\
1.126     brouard  8000:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8001:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8002: 
1.222     brouard  8003:    fprintf(fichtm,"\
1.126     brouard  8004:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8005:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8006:    fprintf(fichtm,"\
1.126     brouard  8007:  - 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): \
                   8008:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8009:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8010:    fprintf(fichtm,"\
1.126     brouard  8011:  - (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): \
                   8012:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8013:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8014:    fprintf(fichtm,"\
1.288     brouard  8015:  - 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  8016:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8017:    fprintf(fichtm,"\
1.128     brouard  8018:  - 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  8019:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8020:    fprintf(fichtm,"\
1.288     brouard  8021:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8022:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8023: 
                   8024: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8025: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8026: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8027: /*     <br>",fileres,fileres,fileres,fileres); */
                   8028: /*  else  */
1.338     brouard  8029: /*    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  8030:    fflush(fichtm);
1.126     brouard  8031: 
1.225     brouard  8032:    m=pow(2,cptcoveff);
1.222     brouard  8033:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8034: 
1.317     brouard  8035:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8036: 
                   8037:   jj1=0;
                   8038: 
                   8039:    fprintf(fichtm," \n<ul>");
1.337     brouard  8040:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8041:      /* k1=nres; */
1.338     brouard  8042:      k1=TKresult[nres];
1.337     brouard  8043:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8044:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8045:      /*   continue; */
1.317     brouard  8046:      jj1++;
                   8047:      if (cptcovn > 0) {
                   8048:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8049:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8050:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8051:        }
                   8052:        fprintf(fichtm,"\">");
                   8053:        
                   8054:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8055:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8056:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8057:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8058:        }
                   8059:        if(invalidvarcomb[k1]){
                   8060:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8061:         continue;
                   8062:        }
                   8063:        fprintf(fichtm,"</a></li>");
                   8064:      } /* cptcovn >0 */
1.337     brouard  8065:    } /* End nres */
1.317     brouard  8066:    fprintf(fichtm," \n</ul>");
                   8067: 
1.222     brouard  8068:    jj1=0;
1.237     brouard  8069: 
1.241     brouard  8070:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8071:      /* k1=nres; */
1.338     brouard  8072:      k1=TKresult[nres];
                   8073:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8074:      /* for(k1=1; k1<=m;k1++){ */
                   8075:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8076:      /*   continue; */
1.222     brouard  8077:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8078:      jj1++;
1.126     brouard  8079:      if (cptcovn > 0) {
1.317     brouard  8080:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8081:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8082:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8083:        }
                   8084:        fprintf(fichtm,"\"</a>");
                   8085:        
1.126     brouard  8086:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8087:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8088:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8089:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8090:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8091:        }
1.237     brouard  8092: 
1.338     brouard  8093:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8094: 
1.222     brouard  8095:        if(invalidvarcomb[k1]){
                   8096:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8097:         continue;
                   8098:        }
1.337     brouard  8099:      } /* If cptcovn >0 */
1.126     brouard  8100:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8101:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8102: 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);
                   8103:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8104:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8105:      }
                   8106:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8107: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8108: true period expectancies (those weighted with period prevalences are also\
                   8109:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8110:  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);
                   8111:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8112:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8113:      /* } /\* end i1 *\/ */
1.241     brouard  8114:   }/* End nres */
1.222     brouard  8115:    fprintf(fichtm,"</ul>");
                   8116:    fflush(fichtm);
1.126     brouard  8117: }
                   8118: 
                   8119: /******************* Gnuplot file **************/
1.296     brouard  8120: 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  8121: 
                   8122:   char dirfileres[132],optfileres[132];
1.264     brouard  8123:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8124:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,kf=0,kvar=0,kk=0,ipos=0,iposold=0,ij=0, ijp=0, l=0;
1.211     brouard  8125:   int lv=0, vlv=0, kl=0;
1.130     brouard  8126:   int ng=0;
1.201     brouard  8127:   int vpopbased;
1.223     brouard  8128:   int ioffset; /* variable offset for columns */
1.270     brouard  8129:   int iyearc=1; /* variable column for year of projection  */
                   8130:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8131:   int nres=0; /* Index of resultline */
1.266     brouard  8132:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8133: 
1.126     brouard  8134: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8135: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8136: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8137: /*   } */
                   8138: 
                   8139:   /*#ifdef windows */
                   8140:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8141:   /*#endif */
1.225     brouard  8142:   m=pow(2,cptcoveff);
1.126     brouard  8143: 
1.274     brouard  8144:   /* diagram of the model */
                   8145:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8146:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8147:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8148:   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);
                   8149: 
1.343     brouard  8150:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] for [j=1:%d] arrow (%d+1)*10+i from cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.80*(cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0)  ), -0.80*(sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) + yoff ) ls 4\n",nlstate, nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
1.274     brouard  8151:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8152:   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);
                   8153:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8154:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8155:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8156:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8157: 
1.202     brouard  8158:   /* Contribution to likelihood */
                   8159:   /* Plot the probability implied in the likelihood */
1.223     brouard  8160:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8161:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8162:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8163:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8164: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8165:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8166: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8167:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8168:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8169:   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));
                   8170:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8171:   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));
                   8172:   for (i=1; i<= nlstate ; i ++) {
                   8173:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8174:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8175:     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);
                   8176:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8177:       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);
                   8178:     }
                   8179:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8180:   }
                   8181:   /* 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 */               
                   8182:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8183:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8184:   fprintf(ficgp,"\nset out;unset log\n");
                   8185:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8186: 
1.343     brouard  8187:   /* Plot the probability implied in the likelihood by covariate value */
                   8188:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8189:   /* if(debugILK==1){ */
                   8190:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   8191:     kvar=Tvar[TvarFind[kf]]; /* variable */
                   8192:     k=18+Tvar[TvarFind[kf]];/*offset because there are 18 columns in the ILK_ file */
                   8193:     for (i=1; i<= nlstate ; i ++) {
                   8194:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8195:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8196:       fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
                   8197:       for (j=2; j<= nlstate+ndeath ; j ++) {
                   8198:        fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
                   8199:       }
                   8200:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8201:     }
                   8202:   } /* End of each covariate dummy */
                   8203:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8204:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8205:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8206:      *  varying                   1     2                                 3       4        5
                   8207:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8208:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8209:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8210:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8211:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8212:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8213:      */
                   8214:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8215:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8216:     /* printf("DebugILK ficgp ncovv=%d, kvar=TvarVV[ncovv]=%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   8217:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8218:       /* printf(" %d",ipos); */
                   8219:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8220:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8221:       kk++; /* Position of the ncovv column in ILK_ */
                   8222:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8223:       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   8224:        for (i=1; i<= nlstate ; i ++) {
                   8225:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8226:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8227: 
                   8228:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8229:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8230:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
                   8231:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8232:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
                   8233:            }
                   8234:          }else{
                   8235:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8236:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
                   8237:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8238:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
                   8239:            }
                   8240:          }
                   8241:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8242:        }
                   8243:       }/* End if dummy varying */
                   8244:     }else{ /*Product */
                   8245:       /* printf("*"); */
                   8246:       /* fprintf(ficresilk,"*"); */
                   8247:     }
                   8248:     iposold=ipos;
                   8249:   } /* For each time varying covariate */
                   8250:   /* } /\* debugILK==1 *\/ */
                   8251:   /* 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 */               
                   8252:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8253:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8254:   fprintf(ficgp,"\nset out;unset log\n");
                   8255:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8256: 
                   8257: 
                   8258:   
1.126     brouard  8259:   strcpy(dirfileres,optionfilefiname);
                   8260:   strcpy(optfileres,"vpl");
1.223     brouard  8261:   /* 1eme*/
1.238     brouard  8262:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8263:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8264:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8265:        k1=TKresult[nres];
1.338     brouard  8266:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8267:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8268:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8269:        /*   continue; */
1.238     brouard  8270:        /* We are interested in selected combination by the resultline */
1.246     brouard  8271:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8272:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8273:        strcpy(gplotlabel,"(");
1.337     brouard  8274:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8275:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8276:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8277: 
                   8278:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8279:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8280:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8281:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8282:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8283:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8284:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8285:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8286:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8287:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8288:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8289:        /* } */
                   8290:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8291:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8292:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8293:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8294:        }
                   8295:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8296:        /* printf("\n#\n"); */
1.238     brouard  8297:        fprintf(ficgp,"\n#\n");
                   8298:        if(invalidvarcomb[k1]){
1.260     brouard  8299:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8300:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8301:          continue;
                   8302:        }
1.235     brouard  8303:       
1.241     brouard  8304:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8305:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8306:        /* 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  8307:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8308:        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);
                   8309:        /* 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); */
                   8310:       /* k1-1 error should be nres-1*/
1.238     brouard  8311:        for (i=1; i<= nlstate ; i ++) {
                   8312:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8313:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8314:        }
1.288     brouard  8315:        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  8316:        for (i=1; i<= nlstate ; i ++) {
                   8317:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8318:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8319:        } 
1.260     brouard  8320:        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  8321:        for (i=1; i<= nlstate ; i ++) {
                   8322:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8323:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8324:        }  
1.265     brouard  8325:        /* 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)); */
                   8326:        
                   8327:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8328:         if(cptcoveff ==0){
1.271     brouard  8329:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8330:        }else{
                   8331:          kl=0;
                   8332:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8333:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8334:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8335:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8336:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8337:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8338:            vlv= nbcode[Tvaraff[k]][lv];
                   8339:            kl++;
                   8340:            /* 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 *\/ */
                   8341:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8342:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8343:            /* ''  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*/
                   8344:            if(k==cptcoveff){
                   8345:              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], \
                   8346:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8347:            }else{
                   8348:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8349:              kl++;
                   8350:            }
                   8351:          } /* end covariate */
                   8352:        } /* end if no covariate */
                   8353: 
1.296     brouard  8354:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8355:          /* 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  8356:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8357:          if(cptcoveff ==0){
1.245     brouard  8358:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8359:          }else{
                   8360:            kl=0;
                   8361:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8362:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8363:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8364:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8365:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8366:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8367:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8368:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8369:              kl++;
1.238     brouard  8370:              /* 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 *\/ */
                   8371:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8372:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8373:              /* ''  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*/
                   8374:              if(k==cptcoveff){
1.245     brouard  8375:                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  8376:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8377:              }else{
1.332     brouard  8378:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8379:                kl++;
                   8380:              }
                   8381:            } /* end covariate */
                   8382:          } /* end if no covariate */
1.296     brouard  8383:          if(prevbcast == 1){
1.268     brouard  8384:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8385:            /* k1-1 error should be nres-1*/
                   8386:            for (i=1; i<= nlstate ; i ++) {
                   8387:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8388:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8389:            }
1.271     brouard  8390:            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  8391:            for (i=1; i<= nlstate ; i ++) {
                   8392:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8393:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8394:            } 
1.276     brouard  8395:            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  8396:            for (i=1; i<= nlstate ; i ++) {
                   8397:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8398:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8399:            } 
1.274     brouard  8400:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8401:          } /* end if backprojcast */
1.296     brouard  8402:        } /* end if prevbcast */
1.276     brouard  8403:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8404:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8405:       } /* nres */
1.337     brouard  8406:     /* } /\* k1 *\/ */
1.201     brouard  8407:   } /* cpt */
1.235     brouard  8408: 
                   8409:   
1.126     brouard  8410:   /*2 eme*/
1.337     brouard  8411:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8412:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8413:       k1=TKresult[nres];
1.338     brouard  8414:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8415:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8416:       /*       continue; */
1.238     brouard  8417:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8418:       strcpy(gplotlabel,"(");
1.337     brouard  8419:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8420:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8421:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8422:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8423:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8424:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8425:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8426:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8427:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8428:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8429:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8430:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8431:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8432:       /* } */
                   8433:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8434:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8435:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8436:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8437:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8438:       }
1.264     brouard  8439:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8440:       fprintf(ficgp,"\n#\n");
1.223     brouard  8441:       if(invalidvarcomb[k1]){
                   8442:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8443:        continue;
                   8444:       }
1.219     brouard  8445:                        
1.241     brouard  8446:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8447:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8448:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8449:        if(vpopbased==0){
1.238     brouard  8450:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8451:        }else
1.238     brouard  8452:          fprintf(ficgp,"\nreplot ");
                   8453:        for (i=1; i<= nlstate+1 ; i ++) {
                   8454:          k=2*i;
1.261     brouard  8455:          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  8456:          for (j=1; j<= nlstate+1 ; j ++) {
                   8457:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8458:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8459:          }   
                   8460:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8461:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8462:          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  8463:          for (j=1; j<= nlstate+1 ; j ++) {
                   8464:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8465:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8466:          }   
                   8467:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8468:          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  8469:          for (j=1; j<= nlstate+1 ; j ++) {
                   8470:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8471:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8472:          }   
                   8473:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8474:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8475:        } /* state */
                   8476:       } /* vpopbased */
1.264     brouard  8477:       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  8478:     } /* end nres */
1.337     brouard  8479:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8480:        
                   8481:        
                   8482:   /*3eme*/
1.337     brouard  8483:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8484:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8485:       k1=TKresult[nres];
1.338     brouard  8486:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8487:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8488:       /*       continue; */
1.238     brouard  8489: 
1.332     brouard  8490:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8491:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8492:        strcpy(gplotlabel,"(");
1.337     brouard  8493:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8494:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8495:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8496:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8497:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8498:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8499:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8500:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8501:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8502:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8503:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8504:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8505:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8506:        /* } */
                   8507:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8508:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8509:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8510:        }
1.264     brouard  8511:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8512:        fprintf(ficgp,"\n#\n");
                   8513:        if(invalidvarcomb[k1]){
                   8514:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8515:          continue;
                   8516:        }
                   8517:                        
                   8518:        /*       k=2+nlstate*(2*cpt-2); */
                   8519:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8520:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8521:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8522:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8523: 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  8524:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8525:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8526:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8527:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8528:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8529:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8530:                                
1.238     brouard  8531:        */
                   8532:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8533:          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  8534:          /*    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  8535:                                
1.238     brouard  8536:        } 
1.261     brouard  8537:        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  8538:       }
1.264     brouard  8539:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8540:     } /* end nres */
1.337     brouard  8541:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8542:   
1.223     brouard  8543:   /* 4eme */
1.201     brouard  8544:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8545:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8546:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8547:       k1=TKresult[nres];
1.338     brouard  8548:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8549:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8550:       /*       continue; */
1.238     brouard  8551:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8552:        strcpy(gplotlabel,"(");
1.337     brouard  8553:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8554:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8555:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8556:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8557:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8558:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8559:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8560:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8561:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8562:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8563:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8564:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8565:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8566:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8567:        /* } */
                   8568:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8569:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8570:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8571:        }       
1.264     brouard  8572:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8573:        fprintf(ficgp,"\n#\n");
                   8574:        if(invalidvarcomb[k1]){
                   8575:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8576:          continue;
1.223     brouard  8577:        }
1.238     brouard  8578:       
1.241     brouard  8579:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8580:        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  8581:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8582: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8583:        k=3;
                   8584:        for (i=1; i<= nlstate ; i ++){
                   8585:          if(i==1){
                   8586:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8587:          }else{
                   8588:            fprintf(ficgp,", '' ");
                   8589:          }
                   8590:          l=(nlstate+ndeath)*(i-1)+1;
                   8591:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8592:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8593:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8594:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8595:        } /* nlstate */
1.264     brouard  8596:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8597:       } /* end cpt state*/ 
                   8598:     } /* end nres */
1.337     brouard  8599:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8600: 
1.220     brouard  8601: /* 5eme */
1.201     brouard  8602:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8603:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8604:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8605:       k1=TKresult[nres];
1.338     brouard  8606:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8607:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8608:       /*       continue; */
1.238     brouard  8609:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8610:        strcpy(gplotlabel,"(");
1.238     brouard  8611:        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  8612:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8613:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8614:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8615:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8616:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8617:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8618:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8619:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8620:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8621:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8622:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8623:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8624:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8625:        /* } */
                   8626:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8627:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8628:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8629:        }       
1.264     brouard  8630:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8631:        fprintf(ficgp,"\n#\n");
                   8632:        if(invalidvarcomb[k1]){
                   8633:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8634:          continue;
                   8635:        }
1.227     brouard  8636:       
1.241     brouard  8637:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8638:        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  8639:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8640: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8641:        k=3;
                   8642:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8643:          if(j==1)
                   8644:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8645:          else
                   8646:            fprintf(ficgp,", '' ");
                   8647:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8648:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8649:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8650:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8651:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8652:        } /* nlstate */
                   8653:        fprintf(ficgp,", '' ");
                   8654:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8655:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8656:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8657:          if(j < nlstate)
                   8658:            fprintf(ficgp,"$%d +",k+l);
                   8659:          else
                   8660:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8661:        }
1.264     brouard  8662:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8663:       } /* end cpt state*/ 
1.337     brouard  8664:     /* } /\* end covariate *\/   */
1.238     brouard  8665:   } /* end nres */
1.227     brouard  8666:   
1.220     brouard  8667: /* 6eme */
1.202     brouard  8668:   /* CV preval stable (period) for each covariate */
1.337     brouard  8669:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8670:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8671:      k1=TKresult[nres];
1.338     brouard  8672:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8673:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8674:      /*  continue; */
1.255     brouard  8675:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8676:       strcpy(gplotlabel,"(");      
1.288     brouard  8677:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8678:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8679:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8680:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8681:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8682:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8683:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8684:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8685:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8686:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8687:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8688:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8689:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8690:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8691:       /* } */
                   8692:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8693:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8694:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8695:       }        
1.264     brouard  8696:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8697:       fprintf(ficgp,"\n#\n");
1.223     brouard  8698:       if(invalidvarcomb[k1]){
1.227     brouard  8699:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8700:        continue;
1.223     brouard  8701:       }
1.227     brouard  8702:       
1.241     brouard  8703:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8704:       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  8705:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8706: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8707:       k=3; /* Offset */
1.255     brouard  8708:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8709:        if(i==1)
                   8710:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8711:        else
                   8712:          fprintf(ficgp,", '' ");
1.255     brouard  8713:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8714:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8715:        for (j=2; j<= nlstate ; j ++)
                   8716:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8717:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8718:       } /* nlstate */
1.264     brouard  8719:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8720:     } /* end cpt state*/ 
                   8721:   } /* end covariate */  
1.227     brouard  8722:   
                   8723:   
1.220     brouard  8724: /* 7eme */
1.296     brouard  8725:   if(prevbcast == 1){
1.288     brouard  8726:     /* CV backward prevalence  for each covariate */
1.337     brouard  8727:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8728:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8729:       k1=TKresult[nres];
1.338     brouard  8730:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8731:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8732:       /*       continue; */
1.268     brouard  8733:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8734:        strcpy(gplotlabel,"(");      
1.288     brouard  8735:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8736:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8737:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8738:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8739:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8740:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8741:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8742:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8743:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8744:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8745:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8746:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8747:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8748:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8749:        /* } */
                   8750:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8751:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8752:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8753:        }       
1.264     brouard  8754:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8755:        fprintf(ficgp,"\n#\n");
                   8756:        if(invalidvarcomb[k1]){
                   8757:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8758:          continue;
                   8759:        }
                   8760:        
1.241     brouard  8761:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8762:        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  8763:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8764: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8765:        k=3; /* Offset */
1.268     brouard  8766:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8767:          if(i==1)
                   8768:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8769:          else
                   8770:            fprintf(ficgp,", '' ");
                   8771:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8772:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8773:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8774:          /* 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  8775:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8776:          /* for (j=2; j<= nlstate ; j ++) */
                   8777:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8778:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8779:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8780:        } /* nlstate */
1.264     brouard  8781:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8782:       } /* end cpt state*/ 
                   8783:     } /* end covariate */  
1.296     brouard  8784:   } /* End if prevbcast */
1.218     brouard  8785:   
1.223     brouard  8786:   /* 8eme */
1.218     brouard  8787:   if(prevfcast==1){
1.288     brouard  8788:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8789:     
1.337     brouard  8790:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8791:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8792:       k1=TKresult[nres];
1.338     brouard  8793:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8794:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8795:       /*       continue; */
1.211     brouard  8796:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8797:        strcpy(gplotlabel,"(");      
1.288     brouard  8798:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8799:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8800:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8801:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8802:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8803:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8804:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8805:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8806:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8807:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8808:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8809:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8810:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8811:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8812:        /* } */
                   8813:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8814:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8815:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8816:        }       
1.264     brouard  8817:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8818:        fprintf(ficgp,"\n#\n");
                   8819:        if(invalidvarcomb[k1]){
                   8820:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8821:          continue;
                   8822:        }
                   8823:        
                   8824:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8825:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8826:        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  8827:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8828: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8829: 
                   8830:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8831:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8832:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8833:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8834:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8835:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8836:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8837:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8838:          if(i==istart){
1.227     brouard  8839:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8840:          }else{
                   8841:            fprintf(ficgp,",\\\n '' ");
                   8842:          }
                   8843:          if(cptcoveff ==0){ /* No covariate */
                   8844:            ioffset=2; /* Age is in 2 */
                   8845:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8846:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8847:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8848:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8849:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8850:            if(i==nlstate+1){
1.270     brouard  8851:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8852:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8853:              fprintf(ficgp,",\\\n '' ");
                   8854:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8855:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8856:                     offyear,                           \
1.268     brouard  8857:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8858:            }else
1.227     brouard  8859:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8860:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8861:          }else{ /* more than 2 covariates */
1.270     brouard  8862:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8863:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8864:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8865:            iyearc=ioffset-1;
                   8866:            iagec=ioffset;
1.227     brouard  8867:            fprintf(ficgp," u %d:(",ioffset); 
                   8868:            kl=0;
                   8869:            strcpy(gplotcondition,"(");
                   8870:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8871:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8872:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8873:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8874:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8875:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8876:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8877:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8878:              kl++;
                   8879:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8880:              kl++;
                   8881:              if(k <cptcoveff && cptcoveff>1)
                   8882:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8883:            }
                   8884:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8885:            /* 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 *\/ */
                   8886:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8887:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8888:            /* ''  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*/
                   8889:            if(i==nlstate+1){
1.270     brouard  8890:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8891:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8892:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8893:              fprintf(ficgp," u %d:(",iagec); 
                   8894:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8895:                      iyearc, iagec, offyear,                           \
                   8896:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8897: /*  '' 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  8898:            }else{
                   8899:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8900:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8901:            }
                   8902:          } /* end if covariate */
                   8903:        } /* nlstate */
1.264     brouard  8904:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8905:       } /* end cpt state*/
                   8906:     } /* end covariate */
                   8907:   } /* End if prevfcast */
1.227     brouard  8908:   
1.296     brouard  8909:   if(prevbcast==1){
1.268     brouard  8910:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8911:     
1.337     brouard  8912:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8913:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8914:      k1=TKresult[nres];
1.338     brouard  8915:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8916:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8917:        /*      continue; */
1.268     brouard  8918:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8919:        strcpy(gplotlabel,"(");      
                   8920:        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  8921:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8922:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8923:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8924:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8925:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8926:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8927:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8928:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8929:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8930:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8931:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8932:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8933:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8934:        /* } */
                   8935:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8936:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8937:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8938:        }       
                   8939:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8940:        fprintf(ficgp,"\n#\n");
                   8941:        if(invalidvarcomb[k1]){
                   8942:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8943:          continue;
                   8944:        }
                   8945:        
                   8946:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8947:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8948:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8949:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8950: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8951: 
                   8952:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8953:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8954:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8955:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8956:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8957:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8958:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8959:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8960:          if(i==istart){
                   8961:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8962:          }else{
                   8963:            fprintf(ficgp,",\\\n '' ");
                   8964:          }
                   8965:          if(cptcoveff ==0){ /* No covariate */
                   8966:            ioffset=2; /* Age is in 2 */
                   8967:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8968:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8969:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8970:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8971:            fprintf(ficgp," u %d:(", ioffset); 
                   8972:            if(i==nlstate+1){
1.270     brouard  8973:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8974:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8975:              fprintf(ficgp,",\\\n '' ");
                   8976:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8977:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8978:                     offbyear,                          \
                   8979:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8980:            }else
                   8981:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8982:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8983:          }else{ /* more than 2 covariates */
1.270     brouard  8984:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8985:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8986:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8987:            iyearc=ioffset-1;
                   8988:            iagec=ioffset;
1.268     brouard  8989:            fprintf(ficgp," u %d:(",ioffset); 
                   8990:            kl=0;
                   8991:            strcpy(gplotcondition,"(");
1.337     brouard  8992:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  8993:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  8994:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   8995:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8996:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8997:                lv=Tvresult[nres][k];
                   8998:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   8999:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9000:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9001:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9002:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9003:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9004:                kl++;
                   9005:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9006:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9007:                kl++;
1.338     brouard  9008:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9009:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9010:              }
1.268     brouard  9011:            }
                   9012:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9013:            /* 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 *\/ */
                   9014:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9015:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9016:            /* ''  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*/
                   9017:            if(i==nlstate+1){
1.270     brouard  9018:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9019:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9020:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9021:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9022:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9023:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9024:                      iyearc,iagec,offbyear,                            \
                   9025:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9026: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9027:            }else{
                   9028:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9029:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9030:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9031:            }
                   9032:          } /* end if covariate */
                   9033:        } /* nlstate */
                   9034:        fprintf(ficgp,"\nset out; unset label;\n");
                   9035:       } /* end cpt state*/
                   9036:     } /* end covariate */
1.296     brouard  9037:   } /* End if prevbcast */
1.268     brouard  9038:   
1.227     brouard  9039:   
1.238     brouard  9040:   /* 9eme writing MLE parameters */
                   9041:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9042:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9043:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9044:     for(k=1; k <=(nlstate+ndeath); k++){
                   9045:       if (k != i) {
1.227     brouard  9046:        fprintf(ficgp,"#   current state %d\n",k);
                   9047:        for(j=1; j <=ncovmodel; j++){
                   9048:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9049:          jk++; 
                   9050:        }
                   9051:        fprintf(ficgp,"\n");
1.126     brouard  9052:       }
                   9053:     }
1.223     brouard  9054:   }
1.187     brouard  9055:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9056:   
1.145     brouard  9057:   /*goto avoid;*/
1.238     brouard  9058:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9059:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9060:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9061:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9062:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9063:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9064:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9065:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9066:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9067:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9068:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9069:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9070:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9071:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9072:   fprintf(ficgp,"#\n");
1.223     brouard  9073:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9074:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9075:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9076:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9077:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9078:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9079:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9080:      /* k1=nres; */
1.338     brouard  9081:       k1=TKresult[nres];
                   9082:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9083:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9084:       strcpy(gplotlabel,"(");
1.276     brouard  9085:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9086:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9087:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9088:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9089:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9090:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9091:       }
                   9092:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9093:       /*       continue; */
                   9094:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9095:       /* strcpy(gplotlabel,"("); */
                   9096:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9097:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9098:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9099:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9100:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9101:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9102:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9103:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9104:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9105:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9106:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9107:       /* } */
                   9108:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9109:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9110:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9111:       /* }      */
1.264     brouard  9112:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9113:       fprintf(ficgp,"\n#\n");
1.264     brouard  9114:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9115:       fprintf(ficgp,"\nset key outside ");
                   9116:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9117:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9118:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9119:       if (ng==1){
                   9120:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9121:        fprintf(ficgp,"\nunset log y");
                   9122:       }else if (ng==2){
                   9123:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9124:        fprintf(ficgp,"\nset log y");
                   9125:       }else if (ng==3){
                   9126:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9127:        fprintf(ficgp,"\nset log y");
                   9128:       }else
                   9129:        fprintf(ficgp,"\nunset title ");
                   9130:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9131:       i=1;
                   9132:       for(k2=1; k2<=nlstate; k2++) {
                   9133:        k3=i;
                   9134:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9135:          if (k != k2){
                   9136:            switch( ng) {
                   9137:            case 1:
                   9138:              if(nagesqr==0)
                   9139:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9140:              else /* nagesqr =1 */
                   9141:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9142:              break;
                   9143:            case 2: /* ng=2 */
                   9144:              if(nagesqr==0)
                   9145:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9146:              else /* nagesqr =1 */
                   9147:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9148:              break;
                   9149:            case 3:
                   9150:              if(nagesqr==0)
                   9151:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9152:              else /* nagesqr =1 */
                   9153:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9154:              break;
                   9155:            }
                   9156:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9157:            ijp=1; /* product no age */
                   9158:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9159:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9160:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9161:              switch(Typevar[j]){
                   9162:              case 1:
                   9163:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9164:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9165:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9166:                      if(DummyV[j]==0){/* Bug valgrind */
                   9167:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9168:                      }else{ /* quantitative */
                   9169:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9170:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9171:                      }
                   9172:                      ij++;
1.268     brouard  9173:                    }
1.237     brouard  9174:                  }
1.329     brouard  9175:                }
                   9176:                break;
                   9177:              case 2:
                   9178:                if(cptcovprod >0){
                   9179:                  if(j==Tprod[ijp]) { /* */ 
                   9180:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9181:                    if(ijp <=cptcovprod) { /* Product */
                   9182:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9183:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9184:                          /* 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)]); */
                   9185:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9186:                        }else{ /* Vn is dummy and Vm is quanti */
                   9187:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9188:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9189:                        }
                   9190:                      }else{ /* Vn*Vm Vn is quanti */
                   9191:                        if(DummyV[Tvard[ijp][2]]==0){
                   9192:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9193:                        }else{ /* Both quanti */
                   9194:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9195:                        }
1.268     brouard  9196:                      }
1.329     brouard  9197:                      ijp++;
1.237     brouard  9198:                    }
1.329     brouard  9199:                  } /* end Tprod */
                   9200:                }
                   9201:                break;
                   9202:              case 0:
                   9203:                /* simple covariate */
1.264     brouard  9204:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9205:                if(Dummy[j]==0){
                   9206:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9207:                }else{ /* quantitative */
                   9208:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9209:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9210:                }
1.329     brouard  9211:               /* end simple */
                   9212:                break;
                   9213:              default:
                   9214:                break;
                   9215:              } /* end switch */
1.237     brouard  9216:            } /* end j */
1.329     brouard  9217:          }else{ /* k=k2 */
                   9218:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9219:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9220:            }else
                   9221:              i=i-ncovmodel;
1.223     brouard  9222:          }
1.227     brouard  9223:          
1.223     brouard  9224:          if(ng != 1){
                   9225:            fprintf(ficgp,")/(1");
1.227     brouard  9226:            
1.264     brouard  9227:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9228:              if(nagesqr==0)
1.264     brouard  9229:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9230:              else /* nagesqr =1 */
1.264     brouard  9231:                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  9232:               
1.223     brouard  9233:              ij=1;
1.329     brouard  9234:              ijp=1;
                   9235:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9236:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9237:                switch(Typevar[j]){
                   9238:                case 1:
                   9239:                  if(cptcovage >0){ 
                   9240:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9241:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9242:                        if(DummyV[j]==0){/* Bug valgrind */
                   9243:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9244:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9245:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9246:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9247:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9248:                        }else{ /* quantitative */
                   9249:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9250:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9251:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9252:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9253:                        }
                   9254:                        ij++;
                   9255:                      }
                   9256:                    }
                   9257:                  }
                   9258:                  break;
                   9259:                case 2:
                   9260:                  if(cptcovprod >0){
                   9261:                    if(j==Tprod[ijp]) { /* */ 
                   9262:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9263:                      if(ijp <=cptcovprod) { /* Product */
                   9264:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9265:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9266:                            /* 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)]); */
                   9267:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9268:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9269:                          }else{ /* Vn is dummy and Vm is quanti */
                   9270:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9271:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9272:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9273:                          }
                   9274:                        }else{ /* Vn*Vm Vn is quanti */
                   9275:                          if(DummyV[Tvard[ijp][2]]==0){
                   9276:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9277:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9278:                          }else{ /* Both quanti */
                   9279:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9280:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9281:                          } 
                   9282:                        }
                   9283:                        ijp++;
                   9284:                      }
                   9285:                    } /* end Tprod */
                   9286:                  } /* end if */
                   9287:                  break;
                   9288:                case 0: 
                   9289:                  /* simple covariate */
                   9290:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9291:                  if(Dummy[j]==0){
                   9292:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9293:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9294:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9295:                  }else{ /* quantitative */
                   9296:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9297:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9298:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9299:                  }
                   9300:                  /* end simple */
                   9301:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9302:                  break;
                   9303:                default:
                   9304:                  break;
                   9305:                } /* end switch */
1.223     brouard  9306:              }
                   9307:              fprintf(ficgp,")");
                   9308:            }
                   9309:            fprintf(ficgp,")");
                   9310:            if(ng ==2)
1.276     brouard  9311:              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  9312:            else /* ng= 3 */
1.276     brouard  9313:              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  9314:           }else{ /* end ng <> 1 */
1.223     brouard  9315:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9316:              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  9317:          }
                   9318:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9319:            fprintf(ficgp,",");
                   9320:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9321:            fprintf(ficgp,",");
                   9322:          i=i+ncovmodel;
                   9323:        } /* end k */
                   9324:       } /* end k2 */
1.276     brouard  9325:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9326:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9327:     } /* end resultline */
1.223     brouard  9328:   } /* end ng */
                   9329:   /* avoid: */
                   9330:   fflush(ficgp); 
1.126     brouard  9331: }  /* end gnuplot */
                   9332: 
                   9333: 
                   9334: /*************** Moving average **************/
1.219     brouard  9335: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9336:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9337:    
1.222     brouard  9338:    int i, cpt, cptcod;
                   9339:    int modcovmax =1;
                   9340:    int mobilavrange, mob;
                   9341:    int iage=0;
1.288     brouard  9342:    int firstA1=0, firstA2=0;
1.222     brouard  9343: 
1.266     brouard  9344:    double sum=0., sumr=0.;
1.222     brouard  9345:    double age;
1.266     brouard  9346:    double *sumnewp, *sumnewm, *sumnewmr;
                   9347:    double *agemingood, *agemaxgood; 
                   9348:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9349:   
                   9350:   
1.278     brouard  9351:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9352:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9353: 
                   9354:    sumnewp = vector(1,ncovcombmax);
                   9355:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9356:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9357:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9358:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9359:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9360:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9361: 
                   9362:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9363:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9364:      sumnewp[cptcod]=0.;
1.266     brouard  9365:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9366:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9367:    }
                   9368:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9369:   
1.266     brouard  9370:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9371:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9372:      else mobilavrange=mobilav;
                   9373:      for (age=bage; age<=fage; age++)
                   9374:        for (i=1; i<=nlstate;i++)
                   9375:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9376:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9377:      /* We keep the original values on the extreme ages bage, fage and for 
                   9378:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9379:        we use a 5 terms etc. until the borders are no more concerned. 
                   9380:      */ 
                   9381:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9382:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9383:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9384:           sumnewm[cptcod]=0.;
                   9385:           for (i=1; i<=nlstate;i++){
1.222     brouard  9386:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9387:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9388:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9389:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9390:             }
                   9391:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9392:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9393:           } /* end i */
                   9394:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9395:         } /* end cptcod */
1.222     brouard  9396:        }/* end age */
                   9397:      }/* end mob */
1.266     brouard  9398:    }else{
                   9399:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9400:      return -1;
1.266     brouard  9401:    }
                   9402: 
                   9403:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9404:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9405:      if(invalidvarcomb[cptcod]){
                   9406:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9407:        continue;
                   9408:      }
1.219     brouard  9409: 
1.266     brouard  9410:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9411:        sumnewm[cptcod]=0.;
                   9412:        sumnewmr[cptcod]=0.;
                   9413:        for (i=1; i<=nlstate;i++){
                   9414:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9415:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9416:        }
                   9417:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9418:         agemingoodr[cptcod]=age;
                   9419:        }
                   9420:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9421:           agemingood[cptcod]=age;
                   9422:        }
                   9423:      } /* age */
                   9424:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9425:        sumnewm[cptcod]=0.;
1.266     brouard  9426:        sumnewmr[cptcod]=0.;
1.222     brouard  9427:        for (i=1; i<=nlstate;i++){
                   9428:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9429:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9430:        }
                   9431:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9432:         agemaxgoodr[cptcod]=age;
1.222     brouard  9433:        }
                   9434:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9435:         agemaxgood[cptcod]=age;
                   9436:        }
                   9437:      } /* age */
                   9438:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9439:      /* but they will change */
1.288     brouard  9440:      firstA1=0;firstA2=0;
1.266     brouard  9441:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9442:        sumnewm[cptcod]=0.;
                   9443:        sumnewmr[cptcod]=0.;
                   9444:        for (i=1; i<=nlstate;i++){
                   9445:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9446:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9447:        }
                   9448:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9449:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9450:           agemaxgoodr[cptcod]=age;  /* age min */
                   9451:           for (i=1; i<=nlstate;i++)
                   9452:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9453:         }else{ /* bad we change the value with the values of good ages */
                   9454:           for (i=1; i<=nlstate;i++){
                   9455:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9456:           } /* i */
                   9457:         } /* end bad */
                   9458:        }else{
                   9459:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9460:           agemaxgood[cptcod]=age;
                   9461:         }else{ /* bad we change the value with the values of good ages */
                   9462:           for (i=1; i<=nlstate;i++){
                   9463:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9464:           } /* i */
                   9465:         } /* end bad */
                   9466:        }/* end else */
                   9467:        sum=0.;sumr=0.;
                   9468:        for (i=1; i<=nlstate;i++){
                   9469:         sum+=mobaverage[(int)age][i][cptcod];
                   9470:         sumr+=probs[(int)age][i][cptcod];
                   9471:        }
                   9472:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9473:         if(!firstA1){
                   9474:           firstA1=1;
                   9475:           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);
                   9476:         }
                   9477:         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  9478:        } /* end bad */
                   9479:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9480:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9481:         if(!firstA2){
                   9482:           firstA2=1;
                   9483:           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);
                   9484:         }
                   9485:         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  9486:        } /* end bad */
                   9487:      }/* age */
1.266     brouard  9488: 
                   9489:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9490:        sumnewm[cptcod]=0.;
1.266     brouard  9491:        sumnewmr[cptcod]=0.;
1.222     brouard  9492:        for (i=1; i<=nlstate;i++){
                   9493:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9494:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9495:        } 
                   9496:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9497:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9498:           agemingoodr[cptcod]=age;
                   9499:           for (i=1; i<=nlstate;i++)
                   9500:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9501:         }else{ /* bad we change the value with the values of good ages */
                   9502:           for (i=1; i<=nlstate;i++){
                   9503:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9504:           } /* i */
                   9505:         } /* end bad */
                   9506:        }else{
                   9507:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9508:           agemingood[cptcod]=age;
                   9509:         }else{ /* bad */
                   9510:           for (i=1; i<=nlstate;i++){
                   9511:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9512:           } /* i */
                   9513:         } /* end bad */
                   9514:        }/* end else */
                   9515:        sum=0.;sumr=0.;
                   9516:        for (i=1; i<=nlstate;i++){
                   9517:         sum+=mobaverage[(int)age][i][cptcod];
                   9518:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9519:        }
1.266     brouard  9520:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9521:         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  9522:        } /* end bad */
                   9523:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9524:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9525:         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  9526:        } /* end bad */
                   9527:      }/* age */
1.266     brouard  9528: 
1.222     brouard  9529:                
                   9530:      for (age=bage; age<=fage; age++){
1.235     brouard  9531:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9532:        sumnewp[cptcod]=0.;
                   9533:        sumnewm[cptcod]=0.;
                   9534:        for (i=1; i<=nlstate;i++){
                   9535:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9536:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9537:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9538:        }
                   9539:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9540:      }
                   9541:      /* printf("\n"); */
                   9542:      /* } */
1.266     brouard  9543: 
1.222     brouard  9544:      /* brutal averaging */
1.266     brouard  9545:      /* for (i=1; i<=nlstate;i++){ */
                   9546:      /*   for (age=1; age<=bage; age++){ */
                   9547:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9548:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9549:      /*   }     */
                   9550:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9551:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9552:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9553:      /*   } */
                   9554:      /* } /\* end i status *\/ */
                   9555:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9556:      /*   for (age=1; age<=AGESUP; age++){ */
                   9557:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9558:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9559:      /*   } */
                   9560:      /* } */
1.222     brouard  9561:    }/* end cptcod */
1.266     brouard  9562:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9563:    free_vector(agemaxgood,1, ncovcombmax);
                   9564:    free_vector(agemingood,1, ncovcombmax);
                   9565:    free_vector(agemingoodr,1, ncovcombmax);
                   9566:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9567:    free_vector(sumnewm,1, ncovcombmax);
                   9568:    free_vector(sumnewp,1, ncovcombmax);
                   9569:    return 0;
                   9570:  }/* End movingaverage */
1.218     brouard  9571:  
1.126     brouard  9572: 
1.296     brouard  9573:  
1.126     brouard  9574: /************** Forecasting ******************/
1.296     brouard  9575: /* 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)*/
                   9576: 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){
                   9577:   /* dateintemean, mean date of interviews
                   9578:      dateprojd, year, month, day of starting projection 
                   9579:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9580:      agemin, agemax range of age
                   9581:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9582:   */
1.296     brouard  9583:   /* double anprojd, mprojd, jprojd; */
                   9584:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9585:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9586:   double agec; /* generic age */
1.296     brouard  9587:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9588:   double *popeffectif,*popcount;
                   9589:   double ***p3mat;
1.218     brouard  9590:   /* double ***mobaverage; */
1.126     brouard  9591:   char fileresf[FILENAMELENGTH];
                   9592: 
                   9593:   agelim=AGESUP;
1.211     brouard  9594:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9595:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9596:      We still use firstpass and lastpass as another selection.
                   9597:   */
1.214     brouard  9598:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9599:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9600:  
1.201     brouard  9601:   strcpy(fileresf,"F_"); 
                   9602:   strcat(fileresf,fileresu);
1.126     brouard  9603:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9604:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9605:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9606:   }
1.235     brouard  9607:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9608:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9609: 
1.225     brouard  9610:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9611: 
                   9612: 
                   9613:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9614:   if (stepm<=12) stepsize=1;
                   9615:   if(estepm < stepm){
                   9616:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9617:   }
1.270     brouard  9618:   else{
                   9619:     hstepm=estepm;   
                   9620:   }
                   9621:   if(estepm > stepm){ /* Yes every two year */
                   9622:     stepsize=2;
                   9623:   }
1.296     brouard  9624:   hstepm=hstepm/stepm;
1.126     brouard  9625: 
1.296     brouard  9626:   
                   9627:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9628:   /*                              fractional in yp1 *\/ */
                   9629:   /* aintmean=yp; */
                   9630:   /* yp2=modf((yp1*12),&yp); */
                   9631:   /* mintmean=yp; */
                   9632:   /* yp1=modf((yp2*30.5),&yp); */
                   9633:   /* jintmean=yp; */
                   9634:   /* if(jintmean==0) jintmean=1; */
                   9635:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9636: 
1.296     brouard  9637: 
                   9638:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9639:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9640:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9641:   i1=pow(2,cptcoveff);
1.126     brouard  9642:   if (cptcovn < 1){i1=1;}
                   9643:   
1.296     brouard  9644:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9645:   
                   9646:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9647:   
1.126     brouard  9648: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9649:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9650:     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  9651:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9652:       continue;
1.227     brouard  9653:     if(invalidvarcomb[k]){
                   9654:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9655:       continue;
                   9656:     }
                   9657:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9658:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9659:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9660:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9661:     }
1.235     brouard  9662:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9663:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9664:     }
1.227     brouard  9665:     fprintf(ficresf," yearproj age");
                   9666:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9667:       for(i=1; i<=nlstate;i++)               
                   9668:        fprintf(ficresf," p%d%d",i,j);
                   9669:       fprintf(ficresf," wp.%d",j);
                   9670:     }
1.296     brouard  9671:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9672:       fprintf(ficresf,"\n");
1.296     brouard  9673:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9674:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9675:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9676:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9677:        nhstepm = nhstepm/hstepm; 
                   9678:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9679:        oldm=oldms;savm=savms;
1.268     brouard  9680:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9681:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9682:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9683:        for (h=0; h<=nhstepm; h++){
                   9684:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9685:            break;
                   9686:          }
                   9687:        }
                   9688:        fprintf(ficresf,"\n");
                   9689:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9690:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9691:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9692:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9693:        
                   9694:        for(j=1; j<=nlstate+ndeath;j++) {
                   9695:          ppij=0.;
                   9696:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9697:            if (mobilav>=1)
                   9698:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9699:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9700:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9701:            }
1.268     brouard  9702:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9703:          } /* end i */
                   9704:          fprintf(ficresf," %.3f", ppij);
                   9705:        }/* end j */
1.227     brouard  9706:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9707:       } /* end agec */
1.266     brouard  9708:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9709:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9710:     } /* end yearp */
                   9711:   } /* end  k */
1.219     brouard  9712:        
1.126     brouard  9713:   fclose(ficresf);
1.215     brouard  9714:   printf("End of Computing forecasting \n");
                   9715:   fprintf(ficlog,"End of Computing forecasting\n");
                   9716: 
1.126     brouard  9717: }
                   9718: 
1.269     brouard  9719: /************** Back Forecasting ******************/
1.296     brouard  9720:  /* 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){ */
                   9721:  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){
                   9722:   /* back1, year, month, day of starting backprojection
1.267     brouard  9723:      agemin, agemax range of age
                   9724:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9725:      anback2 year of end of backprojection (same day and month as back1).
                   9726:      prevacurrent and prev are prevalences.
1.267     brouard  9727:   */
                   9728:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9729:   double agec; /* generic age */
1.302     brouard  9730:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9731:   double *popeffectif,*popcount;
                   9732:   double ***p3mat;
                   9733:   /* double ***mobaverage; */
                   9734:   char fileresfb[FILENAMELENGTH];
                   9735:  
1.268     brouard  9736:   agelim=AGEINF;
1.267     brouard  9737:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9738:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9739:      We still use firstpass and lastpass as another selection.
                   9740:   */
                   9741:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9742:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9743: 
                   9744:   /*Do we need to compute prevalence again?*/
                   9745: 
                   9746:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9747:   
                   9748:   strcpy(fileresfb,"FB_");
                   9749:   strcat(fileresfb,fileresu);
                   9750:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9751:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9752:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9753:   }
                   9754:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9755:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9756:   
                   9757:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9758:   
                   9759:    
                   9760:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9761:   if (stepm<=12) stepsize=1;
                   9762:   if(estepm < stepm){
                   9763:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9764:   }
1.270     brouard  9765:   else{
                   9766:     hstepm=estepm;   
                   9767:   }
                   9768:   if(estepm >= stepm){ /* Yes every two year */
                   9769:     stepsize=2;
                   9770:   }
1.267     brouard  9771:   
                   9772:   hstepm=hstepm/stepm;
1.296     brouard  9773:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9774:   /*                              fractional in yp1 *\/ */
                   9775:   /* aintmean=yp; */
                   9776:   /* yp2=modf((yp1*12),&yp); */
                   9777:   /* mintmean=yp; */
                   9778:   /* yp1=modf((yp2*30.5),&yp); */
                   9779:   /* jintmean=yp; */
                   9780:   /* if(jintmean==0) jintmean=1; */
                   9781:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9782:   
                   9783:   i1=pow(2,cptcoveff);
                   9784:   if (cptcovn < 1){i1=1;}
                   9785:   
1.296     brouard  9786:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9787:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9788:   
                   9789:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9790:   
                   9791:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9792:   for(k=1; k<=i1;k++){
                   9793:     if(i1 != 1 && TKresult[nres]!= k)
                   9794:       continue;
                   9795:     if(invalidvarcomb[k]){
                   9796:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9797:       continue;
                   9798:     }
1.268     brouard  9799:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9800:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9801:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9802:     }
                   9803:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9804:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9805:     }
                   9806:     fprintf(ficresfb," yearbproj age");
                   9807:     for(j=1; j<=nlstate+ndeath;j++){
                   9808:       for(i=1; i<=nlstate;i++)
1.268     brouard  9809:        fprintf(ficresfb," b%d%d",i,j);
                   9810:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9811:     }
1.296     brouard  9812:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9813:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9814:       fprintf(ficresfb,"\n");
1.296     brouard  9815:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9816:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9817:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9818:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9819:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9820:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9821:        nhstepm = nhstepm/hstepm;
                   9822:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9823:        oldm=oldms;savm=savms;
1.268     brouard  9824:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9825:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9826:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9827:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9828:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9829:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9830:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9831:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9832:            break;
                   9833:          }
                   9834:        }
                   9835:        fprintf(ficresfb,"\n");
                   9836:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9837:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9838:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9839:        for(i=1; i<=nlstate+ndeath;i++) {
                   9840:          ppij=0.;ppi=0.;
                   9841:          for(j=1; j<=nlstate;j++) {
                   9842:            /* if (mobilav==1) */
1.269     brouard  9843:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9844:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9845:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9846:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9847:              /* else { */
                   9848:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9849:              /* } */
1.268     brouard  9850:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9851:          } /* end j */
                   9852:          if(ppi <0.99){
                   9853:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9854:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9855:          }
                   9856:          fprintf(ficresfb," %.3f", ppij);
                   9857:        }/* end j */
1.267     brouard  9858:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9859:       } /* end agec */
                   9860:     } /* end yearp */
                   9861:   } /* end k */
1.217     brouard  9862:   
1.267     brouard  9863:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9864:   
1.267     brouard  9865:   fclose(ficresfb);
                   9866:   printf("End of Computing Back forecasting \n");
                   9867:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9868:        
1.267     brouard  9869: }
1.217     brouard  9870: 
1.269     brouard  9871: /* Variance of prevalence limit: varprlim */
                   9872:  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  9873:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9874:  
                   9875:    char fileresvpl[FILENAMELENGTH];  
                   9876:    FILE *ficresvpl;
                   9877:    double **oldm, **savm;
                   9878:    double **varpl; /* Variances of prevalence limits by age */   
                   9879:    int i1, k, nres, j ;
                   9880:    
                   9881:     strcpy(fileresvpl,"VPL_");
                   9882:     strcat(fileresvpl,fileresu);
                   9883:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9884:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9885:       exit(0);
                   9886:     }
1.288     brouard  9887:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9888:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9889:     
                   9890:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9891:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9892:     
                   9893:     i1=pow(2,cptcoveff);
                   9894:     if (cptcovn < 1){i1=1;}
                   9895: 
1.337     brouard  9896:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9897:        k=TKresult[nres];
1.338     brouard  9898:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9899:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9900:       if(i1 != 1 && TKresult[nres]!= k)
                   9901:        continue;
                   9902:       fprintf(ficresvpl,"\n#****** ");
                   9903:       printf("\n#****** ");
                   9904:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9905:       for(j=1;j<=cptcovs;j++) {
                   9906:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9907:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9908:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9909:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9910:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9911:       }
1.337     brouard  9912:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9913:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9914:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9915:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9916:       /* }      */
1.269     brouard  9917:       fprintf(ficresvpl,"******\n");
                   9918:       printf("******\n");
                   9919:       fprintf(ficlog,"******\n");
                   9920:       
                   9921:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9922:       oldm=oldms;savm=savms;
                   9923:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9924:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9925:       /*}*/
                   9926:     }
                   9927:     
                   9928:     fclose(ficresvpl);
1.288     brouard  9929:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9930:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9931: 
                   9932:  }
                   9933: /* Variance of back prevalence: varbprlim */
                   9934:  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){
                   9935:       /*------- Variance of back (stable) prevalence------*/
                   9936: 
                   9937:    char fileresvbl[FILENAMELENGTH];  
                   9938:    FILE  *ficresvbl;
                   9939: 
                   9940:    double **oldm, **savm;
                   9941:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9942:    int i1, k, nres, j ;
                   9943: 
                   9944:    strcpy(fileresvbl,"VBL_");
                   9945:    strcat(fileresvbl,fileresu);
                   9946:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9947:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9948:      exit(0);
                   9949:    }
                   9950:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9951:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9952:    
                   9953:    
                   9954:    i1=pow(2,cptcoveff);
                   9955:    if (cptcovn < 1){i1=1;}
                   9956:    
1.337     brouard  9957:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9958:      k=TKresult[nres];
1.338     brouard  9959:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9960:     /* for(k=1; k<=i1;k++){ */
                   9961:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9962:     /*          continue; */
1.269     brouard  9963:        fprintf(ficresvbl,"\n#****** ");
                   9964:        printf("\n#****** ");
                   9965:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9966:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  9967:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9968:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9969:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  9970:        /* for(j=1;j<=cptcoveff;j++) { */
                   9971:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9972:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9973:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9974:        /* } */
                   9975:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9976:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9977:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9978:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  9979:        }
                   9980:        fprintf(ficresvbl,"******\n");
                   9981:        printf("******\n");
                   9982:        fprintf(ficlog,"******\n");
                   9983:        
                   9984:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9985:        oldm=oldms;savm=savms;
                   9986:        
                   9987:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9988:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9989:        /*}*/
                   9990:      }
                   9991:    
                   9992:    fclose(ficresvbl);
                   9993:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9994:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9995: 
                   9996:  } /* End of varbprlim */
                   9997: 
1.126     brouard  9998: /************** Forecasting *****not tested NB*************/
1.227     brouard  9999: /* 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  10000:   
1.227     brouard  10001: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10002: /*   int *popage; */
                   10003: /*   double calagedatem, agelim, kk1, kk2; */
                   10004: /*   double *popeffectif,*popcount; */
                   10005: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10006: /*   /\* double ***mobaverage; *\/ */
                   10007: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10008: 
1.227     brouard  10009: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10010: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10011: /*   agelim=AGESUP; */
                   10012: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10013:   
1.227     brouard  10014: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10015:   
                   10016:   
1.227     brouard  10017: /*   strcpy(filerespop,"POP_");  */
                   10018: /*   strcat(filerespop,fileresu); */
                   10019: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10020: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10021: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10022: /*   } */
                   10023: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10024: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10025: 
1.227     brouard  10026: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10027: 
1.227     brouard  10028: /*   /\* if (mobilav!=0) { *\/ */
                   10029: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10030: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10031: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10032: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10033: /*   /\*   } *\/ */
                   10034: /*   /\* } *\/ */
1.126     brouard  10035: 
1.227     brouard  10036: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10037: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10038:   
1.227     brouard  10039: /*   agelim=AGESUP; */
1.126     brouard  10040:   
1.227     brouard  10041: /*   hstepm=1; */
                   10042: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10043:        
1.227     brouard  10044: /*   if (popforecast==1) { */
                   10045: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10046: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10047: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10048: /*     }  */
                   10049: /*     popage=ivector(0,AGESUP); */
                   10050: /*     popeffectif=vector(0,AGESUP); */
                   10051: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10052:     
1.227     brouard  10053: /*     i=1;    */
                   10054: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10055:     
1.227     brouard  10056: /*     imx=i; */
                   10057: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10058: /*   } */
1.218     brouard  10059:   
1.227     brouard  10060: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10061: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10062: /*       k=k+1; */
                   10063: /*       fprintf(ficrespop,"\n#******"); */
                   10064: /*       for(j=1;j<=cptcoveff;j++) { */
                   10065: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10066: /*       } */
                   10067: /*       fprintf(ficrespop,"******\n"); */
                   10068: /*       fprintf(ficrespop,"# Age"); */
                   10069: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10070: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10071:       
1.227     brouard  10072: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10073: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10074:        
1.227     brouard  10075: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10076: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10077: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10078:          
1.227     brouard  10079: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10080: /*       oldm=oldms;savm=savms; */
                   10081: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10082:          
1.227     brouard  10083: /*       for (h=0; h<=nhstepm; h++){ */
                   10084: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10085: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10086: /*         }  */
                   10087: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10088: /*           kk1=0.;kk2=0; */
                   10089: /*           for(i=1; i<=nlstate;i++) {               */
                   10090: /*             if (mobilav==1)  */
                   10091: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10092: /*             else { */
                   10093: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10094: /*             } */
                   10095: /*           } */
                   10096: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10097: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10098: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10099: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10100: /*           } */
                   10101: /*         } */
                   10102: /*         for(i=1; i<=nlstate;i++){ */
                   10103: /*           kk1=0.; */
                   10104: /*           for(j=1; j<=nlstate;j++){ */
                   10105: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10106: /*           } */
                   10107: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10108: /*         } */
1.218     brouard  10109:            
1.227     brouard  10110: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10111: /*           for(j=1; j<=nlstate;j++)  */
                   10112: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10113: /*       } */
                   10114: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10115: /*     } */
                   10116: /*       } */
1.218     brouard  10117:       
1.227     brouard  10118: /*       /\******\/ */
1.218     brouard  10119:       
1.227     brouard  10120: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10121: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10122: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10123: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10124: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10125:          
1.227     brouard  10126: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10127: /*       oldm=oldms;savm=savms; */
                   10128: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10129: /*       for (h=0; h<=nhstepm; h++){ */
                   10130: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10131: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10132: /*         }  */
                   10133: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10134: /*           kk1=0.;kk2=0; */
                   10135: /*           for(i=1; i<=nlstate;i++) {               */
                   10136: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10137: /*           } */
                   10138: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10139: /*         } */
                   10140: /*       } */
                   10141: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10142: /*     } */
                   10143: /*       } */
                   10144: /*     }  */
                   10145: /*   } */
1.218     brouard  10146:   
1.227     brouard  10147: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10148:   
1.227     brouard  10149: /*   if (popforecast==1) { */
                   10150: /*     free_ivector(popage,0,AGESUP); */
                   10151: /*     free_vector(popeffectif,0,AGESUP); */
                   10152: /*     free_vector(popcount,0,AGESUP); */
                   10153: /*   } */
                   10154: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10155: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10156: /*   fclose(ficrespop); */
                   10157: /* } /\* End of popforecast *\/ */
1.218     brouard  10158:  
1.126     brouard  10159: int fileappend(FILE *fichier, char *optionfich)
                   10160: {
                   10161:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10162:     printf("Problem with file: %s\n", optionfich);
                   10163:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10164:     return (0);
                   10165:   }
                   10166:   fflush(fichier);
                   10167:   return (1);
                   10168: }
                   10169: 
                   10170: 
                   10171: /**************** function prwizard **********************/
                   10172: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10173: {
                   10174: 
                   10175:   /* Wizard to print covariance matrix template */
                   10176: 
1.164     brouard  10177:   char ca[32], cb[32];
                   10178:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10179:   int numlinepar;
                   10180: 
                   10181:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10182:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10183:   for(i=1; i <=nlstate; i++){
                   10184:     jj=0;
                   10185:     for(j=1; j <=nlstate+ndeath; j++){
                   10186:       if(j==i) continue;
                   10187:       jj++;
                   10188:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10189:       printf("%1d%1d",i,j);
                   10190:       fprintf(ficparo,"%1d%1d",i,j);
                   10191:       for(k=1; k<=ncovmodel;k++){
                   10192:        /*        printf(" %lf",param[i][j][k]); */
                   10193:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10194:        printf(" 0.");
                   10195:        fprintf(ficparo," 0.");
                   10196:       }
                   10197:       printf("\n");
                   10198:       fprintf(ficparo,"\n");
                   10199:     }
                   10200:   }
                   10201:   printf("# Scales (for hessian or gradient estimation)\n");
                   10202:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10203:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10204:   for(i=1; i <=nlstate; i++){
                   10205:     jj=0;
                   10206:     for(j=1; j <=nlstate+ndeath; j++){
                   10207:       if(j==i) continue;
                   10208:       jj++;
                   10209:       fprintf(ficparo,"%1d%1d",i,j);
                   10210:       printf("%1d%1d",i,j);
                   10211:       fflush(stdout);
                   10212:       for(k=1; k<=ncovmodel;k++){
                   10213:        /*      printf(" %le",delti3[i][j][k]); */
                   10214:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10215:        printf(" 0.");
                   10216:        fprintf(ficparo," 0.");
                   10217:       }
                   10218:       numlinepar++;
                   10219:       printf("\n");
                   10220:       fprintf(ficparo,"\n");
                   10221:     }
                   10222:   }
                   10223:   printf("# Covariance matrix\n");
                   10224: /* # 121 Var(a12)\n\ */
                   10225: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10226: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10227: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10228: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10229: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10230: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10231: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10232:   fflush(stdout);
                   10233:   fprintf(ficparo,"# Covariance matrix\n");
                   10234:   /* # 121 Var(a12)\n\ */
                   10235:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10236:   /* #   ...\n\ */
                   10237:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10238:   
                   10239:   for(itimes=1;itimes<=2;itimes++){
                   10240:     jj=0;
                   10241:     for(i=1; i <=nlstate; i++){
                   10242:       for(j=1; j <=nlstate+ndeath; j++){
                   10243:        if(j==i) continue;
                   10244:        for(k=1; k<=ncovmodel;k++){
                   10245:          jj++;
                   10246:          ca[0]= k+'a'-1;ca[1]='\0';
                   10247:          if(itimes==1){
                   10248:            printf("#%1d%1d%d",i,j,k);
                   10249:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10250:          }else{
                   10251:            printf("%1d%1d%d",i,j,k);
                   10252:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10253:            /*  printf(" %.5le",matcov[i][j]); */
                   10254:          }
                   10255:          ll=0;
                   10256:          for(li=1;li <=nlstate; li++){
                   10257:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10258:              if(lj==li) continue;
                   10259:              for(lk=1;lk<=ncovmodel;lk++){
                   10260:                ll++;
                   10261:                if(ll<=jj){
                   10262:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10263:                  if(ll<jj){
                   10264:                    if(itimes==1){
                   10265:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10266:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10267:                    }else{
                   10268:                      printf(" 0.");
                   10269:                      fprintf(ficparo," 0.");
                   10270:                    }
                   10271:                  }else{
                   10272:                    if(itimes==1){
                   10273:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10274:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10275:                    }else{
                   10276:                      printf(" 0.");
                   10277:                      fprintf(ficparo," 0.");
                   10278:                    }
                   10279:                  }
                   10280:                }
                   10281:              } /* end lk */
                   10282:            } /* end lj */
                   10283:          } /* end li */
                   10284:          printf("\n");
                   10285:          fprintf(ficparo,"\n");
                   10286:          numlinepar++;
                   10287:        } /* end k*/
                   10288:       } /*end j */
                   10289:     } /* end i */
                   10290:   } /* end itimes */
                   10291: 
                   10292: } /* end of prwizard */
                   10293: /******************* Gompertz Likelihood ******************************/
                   10294: double gompertz(double x[])
                   10295: { 
1.302     brouard  10296:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10297:   int i,n=0; /* n is the size of the sample */
                   10298: 
1.220     brouard  10299:   for (i=1;i<=imx ; i++) {
1.126     brouard  10300:     sump=sump+weight[i];
                   10301:     /*    sump=sump+1;*/
                   10302:     num=num+1;
                   10303:   }
1.302     brouard  10304:   L=0.0;
                   10305:   /* agegomp=AGEGOMP; */
1.126     brouard  10306:   /* for (i=0; i<=imx; i++) 
                   10307:      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]);*/
                   10308: 
1.302     brouard  10309:   for (i=1;i<=imx ; i++) {
                   10310:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10311:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10312:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10313:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10314:      * +
                   10315:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10316:      */
                   10317:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10318:        if (cens[i] == 1){
                   10319:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10320:        } else if (cens[i] == 0){
1.126     brouard  10321:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10322:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10323:       } else
                   10324:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10325:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10326:        L=L+A*weight[i];
1.126     brouard  10327:        /*      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  10328:      }
                   10329:   }
1.126     brouard  10330: 
1.302     brouard  10331:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10332:  
                   10333:   return -2*L*num/sump;
                   10334: }
                   10335: 
1.136     brouard  10336: #ifdef GSL
                   10337: /******************* Gompertz_f Likelihood ******************************/
                   10338: double gompertz_f(const gsl_vector *v, void *params)
                   10339: { 
1.302     brouard  10340:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10341:   double *x= (double *) v->data;
                   10342:   int i,n=0; /* n is the size of the sample */
                   10343: 
                   10344:   for (i=0;i<=imx-1 ; i++) {
                   10345:     sump=sump+weight[i];
                   10346:     /*    sump=sump+1;*/
                   10347:     num=num+1;
                   10348:   }
                   10349:  
                   10350:  
                   10351:   /* for (i=0; i<=imx; i++) 
                   10352:      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]);*/
                   10353:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10354:   for (i=1;i<=imx ; i++)
                   10355:     {
                   10356:       if (cens[i] == 1 && wav[i]>1)
                   10357:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10358:       
                   10359:       if (cens[i] == 0 && wav[i]>1)
                   10360:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10361:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10362:       
                   10363:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10364:       if (wav[i] > 1 ) { /* ??? */
                   10365:        LL=LL+A*weight[i];
                   10366:        /*      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]);*/
                   10367:       }
                   10368:     }
                   10369: 
                   10370:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10371:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10372:  
                   10373:   return -2*LL*num/sump;
                   10374: }
                   10375: #endif
                   10376: 
1.126     brouard  10377: /******************* Printing html file ***********/
1.201     brouard  10378: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10379:                  int lastpass, int stepm, int weightopt, char model[],\
                   10380:                  int imx,  double p[],double **matcov,double agemortsup){
                   10381:   int i,k;
                   10382: 
                   10383:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10384:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10385:   for (i=1;i<=2;i++) 
                   10386:     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  10387:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10388:   fprintf(fichtm,"</ul>");
                   10389: 
                   10390: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10391: 
                   10392:  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>");
                   10393: 
                   10394:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10395:    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]);
                   10396: 
                   10397:  
                   10398:   fflush(fichtm);
                   10399: }
                   10400: 
                   10401: /******************* Gnuplot file **************/
1.201     brouard  10402: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10403: 
                   10404:   char dirfileres[132],optfileres[132];
1.164     brouard  10405: 
1.126     brouard  10406:   int ng;
                   10407: 
                   10408: 
                   10409:   /*#ifdef windows */
                   10410:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10411:     /*#endif */
                   10412: 
                   10413: 
                   10414:   strcpy(dirfileres,optionfilefiname);
                   10415:   strcpy(optfileres,"vpl");
1.199     brouard  10416:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10417:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10418:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10419:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10420:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10421: 
                   10422: } 
                   10423: 
1.136     brouard  10424: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10425: {
1.126     brouard  10426: 
1.136     brouard  10427:   /*-------- data file ----------*/
                   10428:   FILE *fic;
                   10429:   char dummy[]="                         ";
1.240     brouard  10430:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10431:   int lstra;
1.136     brouard  10432:   int linei, month, year,iout;
1.302     brouard  10433:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10434:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10435:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10436:   char *stratrunc;
1.223     brouard  10437: 
1.240     brouard  10438:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10439:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10440:   for(v=1;v<NCOVMAX;v++){
                   10441:     DummyV[v]=0;
                   10442:     FixedV[v]=0;
                   10443:   }
1.126     brouard  10444: 
1.240     brouard  10445:   for(v=1; v <=ncovcol;v++){
                   10446:     DummyV[v]=0;
                   10447:     FixedV[v]=0;
                   10448:   }
                   10449:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10450:     DummyV[v]=1;
                   10451:     FixedV[v]=0;
                   10452:   }
                   10453:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10454:     DummyV[v]=0;
                   10455:     FixedV[v]=1;
                   10456:   }
                   10457:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10458:     DummyV[v]=1;
                   10459:     FixedV[v]=1;
                   10460:   }
                   10461:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10462:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10463:     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]);
                   10464:   }
1.339     brouard  10465:   
                   10466:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10467:   
1.136     brouard  10468:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10469:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10470:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10471:   }
1.126     brouard  10472: 
1.302     brouard  10473:     /* Is it a BOM UTF-8 Windows file? */
                   10474:   /* First data line */
                   10475:   linei=0;
                   10476:   while(fgets(line, MAXLINE, fic)) {
                   10477:     noffset=0;
                   10478:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10479:     {
                   10480:       noffset=noffset+3;
                   10481:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10482:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10483:       fflush(ficlog); return 1;
                   10484:     }
                   10485:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10486:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10487:     {
                   10488:       noffset=noffset+2;
1.304     brouard  10489:       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);
                   10490:       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  10491:       fflush(ficlog); return 1;
                   10492:     }
                   10493:     else if( line[0] == 0 && line[1] == 0)
                   10494:     {
                   10495:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10496:        noffset=noffset+4;
1.304     brouard  10497:        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);
                   10498:        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  10499:        fflush(ficlog); return 1;
                   10500:       }
                   10501:     } else{
                   10502:       ;/*printf(" Not a BOM file\n");*/
                   10503:     }
                   10504:         /* If line starts with a # it is a comment */
                   10505:     if (line[noffset] == '#') {
                   10506:       linei=linei+1;
                   10507:       break;
                   10508:     }else{
                   10509:       break;
                   10510:     }
                   10511:   }
                   10512:   fclose(fic);
                   10513:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10514:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10515:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10516:   }
                   10517:   /* Not a Bom file */
                   10518:   
1.136     brouard  10519:   i=1;
                   10520:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10521:     linei=linei+1;
                   10522:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10523:       if(line[j] == '\t')
                   10524:        line[j] = ' ';
                   10525:     }
                   10526:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10527:       ;
                   10528:     };
                   10529:     line[j+1]=0;  /* Trims blanks at end of line */
                   10530:     if(line[0]=='#'){
                   10531:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10532:       printf("Comment line\n%s\n",line);
                   10533:       continue;
                   10534:     }
                   10535:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10536:     strcpy(line, linetmp);
1.223     brouard  10537:     
                   10538:     /* Loops on waves */
                   10539:     for (j=maxwav;j>=1;j--){
                   10540:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10541:        cutv(stra, strb, line, ' '); 
                   10542:        if(strb[0]=='.') { /* Missing value */
                   10543:          lval=-1;
                   10544:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10545:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10546:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10547:            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);
                   10548:            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);
                   10549:            return 1;
                   10550:          }
                   10551:        }else{
                   10552:          errno=0;
                   10553:          /* what_kind_of_number(strb); */
                   10554:          dval=strtod(strb,&endptr); 
                   10555:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10556:          /* if(strb != endptr && *endptr == '\0') */
                   10557:          /*    dval=dlval; */
                   10558:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10559:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10560:            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);
                   10561:            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);
                   10562:            return 1;
                   10563:          }
                   10564:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10565:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10566:        }
                   10567:        strcpy(line,stra);
1.223     brouard  10568:       }/* end loop ntqv */
1.225     brouard  10569:       
1.223     brouard  10570:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10571:        cutv(stra, strb, line, ' '); 
                   10572:        if(strb[0]=='.') { /* Missing value */
                   10573:          lval=-1;
                   10574:        }else{
                   10575:          errno=0;
                   10576:          lval=strtol(strb,&endptr,10); 
                   10577:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10578:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10579:            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);
                   10580:            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);
                   10581:            return 1;
                   10582:          }
                   10583:        }
                   10584:        if(lval <-1 || lval >1){
                   10585:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10586:  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  10587:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10588:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10589:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10590:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10591:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10592:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10593:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10594:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10595:  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  10596:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10597:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10598:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10599:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10600:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10601:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10602:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10603:          return 1;
                   10604:        }
1.341     brouard  10605:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10606:        strcpy(line,stra);
1.223     brouard  10607:       }/* end loop ntv */
1.225     brouard  10608:       
1.223     brouard  10609:       /* Statuses  at wave */
1.137     brouard  10610:       cutv(stra, strb, line, ' '); 
1.223     brouard  10611:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10612:        lval=-1;
1.136     brouard  10613:       }else{
1.238     brouard  10614:        errno=0;
                   10615:        lval=strtol(strb,&endptr,10); 
                   10616:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10617:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10618:          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);
                   10619:          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);
                   10620:          return 1;
                   10621:        }
1.136     brouard  10622:       }
1.225     brouard  10623:       
1.136     brouard  10624:       s[j][i]=lval;
1.225     brouard  10625:       
1.223     brouard  10626:       /* Date of Interview */
1.136     brouard  10627:       strcpy(line,stra);
                   10628:       cutv(stra, strb,line,' ');
1.169     brouard  10629:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10630:       }
1.169     brouard  10631:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10632:        month=99;
                   10633:        year=9999;
1.136     brouard  10634:       }else{
1.225     brouard  10635:        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);
                   10636:        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);
                   10637:        return 1;
1.136     brouard  10638:       }
                   10639:       anint[j][i]= (double) year; 
1.302     brouard  10640:       mint[j][i]= (double)month;
                   10641:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10642:       /*       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]); */
                   10643:       /*       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]); */
                   10644:       /* } */
1.136     brouard  10645:       strcpy(line,stra);
1.223     brouard  10646:     } /* End loop on waves */
1.225     brouard  10647:     
1.223     brouard  10648:     /* Date of death */
1.136     brouard  10649:     cutv(stra, strb,line,' '); 
1.169     brouard  10650:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10651:     }
1.169     brouard  10652:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10653:       month=99;
                   10654:       year=9999;
                   10655:     }else{
1.141     brouard  10656:       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  10657:       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);
                   10658:       return 1;
1.136     brouard  10659:     }
                   10660:     andc[i]=(double) year; 
                   10661:     moisdc[i]=(double) month; 
                   10662:     strcpy(line,stra);
                   10663:     
1.223     brouard  10664:     /* Date of birth */
1.136     brouard  10665:     cutv(stra, strb,line,' '); 
1.169     brouard  10666:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10667:     }
1.169     brouard  10668:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10669:       month=99;
                   10670:       year=9999;
                   10671:     }else{
1.141     brouard  10672:       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);
                   10673:       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  10674:       return 1;
1.136     brouard  10675:     }
                   10676:     if (year==9999) {
1.141     brouard  10677:       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);
                   10678:       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  10679:       return 1;
                   10680:       
1.136     brouard  10681:     }
                   10682:     annais[i]=(double)(year);
1.302     brouard  10683:     moisnais[i]=(double)(month);
                   10684:     for (j=1;j<=maxwav;j++){
                   10685:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10686:        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]);
                   10687:        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]);
                   10688:       }
                   10689:     }
                   10690: 
1.136     brouard  10691:     strcpy(line,stra);
1.225     brouard  10692:     
1.223     brouard  10693:     /* Sample weight */
1.136     brouard  10694:     cutv(stra, strb,line,' '); 
                   10695:     errno=0;
                   10696:     dval=strtod(strb,&endptr); 
                   10697:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10698:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10699:       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  10700:       fflush(ficlog);
                   10701:       return 1;
                   10702:     }
                   10703:     weight[i]=dval; 
                   10704:     strcpy(line,stra);
1.225     brouard  10705:     
1.223     brouard  10706:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10707:       cutv(stra, strb, line, ' '); 
                   10708:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10709:        lval=-1;
1.311     brouard  10710:        coqvar[iv][i]=NAN; 
                   10711:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10712:       }else{
1.225     brouard  10713:        errno=0;
                   10714:        /* what_kind_of_number(strb); */
                   10715:        dval=strtod(strb,&endptr);
                   10716:        /* if(strb != endptr && *endptr == '\0') */
                   10717:        /*   dval=dlval; */
                   10718:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10719:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10720:          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);
                   10721:          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);
                   10722:          return 1;
                   10723:        }
                   10724:        coqvar[iv][i]=dval; 
1.226     brouard  10725:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10726:       }
                   10727:       strcpy(line,stra);
                   10728:     }/* end loop nqv */
1.136     brouard  10729:     
1.223     brouard  10730:     /* Covariate values */
1.136     brouard  10731:     for (j=ncovcol;j>=1;j--){
                   10732:       cutv(stra, strb,line,' '); 
1.223     brouard  10733:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10734:        lval=-1;
1.136     brouard  10735:       }else{
1.225     brouard  10736:        errno=0;
                   10737:        lval=strtol(strb,&endptr,10); 
                   10738:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10739:          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);
                   10740:          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);
                   10741:          return 1;
                   10742:        }
1.136     brouard  10743:       }
                   10744:       if(lval <-1 || lval >1){
1.225     brouard  10745:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10746:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10747:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10748:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10749:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10750:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10751:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10752:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10753:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10754:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10755:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10756:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10757:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10758:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10759:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10760:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10761:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10762:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10763:        return 1;
1.136     brouard  10764:       }
                   10765:       covar[j][i]=(double)(lval);
                   10766:       strcpy(line,stra);
                   10767:     }  
                   10768:     lstra=strlen(stra);
1.225     brouard  10769:     
1.136     brouard  10770:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10771:       stratrunc = &(stra[lstra-9]);
                   10772:       num[i]=atol(stratrunc);
                   10773:     }
                   10774:     else
                   10775:       num[i]=atol(stra);
                   10776:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10777:       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;}*/
                   10778:     
                   10779:     i=i+1;
                   10780:   } /* End loop reading  data */
1.225     brouard  10781:   
1.136     brouard  10782:   *imax=i-1; /* Number of individuals */
                   10783:   fclose(fic);
1.225     brouard  10784:   
1.136     brouard  10785:   return (0);
1.164     brouard  10786:   /* endread: */
1.225     brouard  10787:   printf("Exiting readdata: ");
                   10788:   fclose(fic);
                   10789:   return (1);
1.223     brouard  10790: }
1.126     brouard  10791: 
1.234     brouard  10792: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10793:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10794:   while (*p2 == ' ')
1.234     brouard  10795:     p2++; 
                   10796:   /* while ((*p1++ = *p2++) !=0) */
                   10797:   /*   ; */
                   10798:   /* do */
                   10799:   /*   while (*p2 == ' ') */
                   10800:   /*     p2++; */
                   10801:   /* while (*p1++ == *p2++); */
                   10802:   *stri=p2; 
1.145     brouard  10803: }
                   10804: 
1.330     brouard  10805: int decoderesult( char resultline[], int nres)
1.230     brouard  10806: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10807: {
1.235     brouard  10808:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10809:   char resultsav[MAXLINE];
1.330     brouard  10810:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10811:   /* int modelresult[MAXLINE]; */
1.230     brouard  10812:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10813: 
1.234     brouard  10814:   removefirstspace(&resultline);
1.332     brouard  10815:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10816: 
1.332     brouard  10817:   strcpy(resultsav,resultline);
1.342     brouard  10818:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  10819:   if (strlen(resultsav) >1){
1.334     brouard  10820:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10821:   }
1.253     brouard  10822:   if(j == 0){ /* Resultline but no = */
                   10823:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10824:     return (0);
                   10825:   }
1.234     brouard  10826:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10827:     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);
                   10828:     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  10829:     /* return 1;*/
1.234     brouard  10830:   }
1.334     brouard  10831:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10832:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10833:       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  10834:       /* 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  10835:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10836:       /* If a blank, then strc="V4=" and strd='\0' */
                   10837:       if(strc[0]=='\0'){
                   10838:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10839:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10840:        return 1;
                   10841:       }
1.234     brouard  10842:     }else
                   10843:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10844:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10845:     
1.230     brouard  10846:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10847:     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  10848:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10849:     /* cptcovsel++;     */
                   10850:     if (nbocc(stra,'=') >0)
                   10851:       strcpy(resultsav,stra); /* and analyzes it */
                   10852:   }
1.235     brouard  10853:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10854:   /* 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  10855:   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  10856:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10857:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10858:       match=0;
1.318     brouard  10859:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10860:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10861:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10862:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10863:          break;
                   10864:        }
                   10865:       }
                   10866:       if(match == 0){
1.338     brouard  10867:        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]);
                   10868:        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  10869:        return 1;
1.234     brouard  10870:       }
1.332     brouard  10871:     }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*/
                   10872:       /* We feed resultmodel[k1]=k2; */
                   10873:       match=0;
                   10874:       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 */
                   10875:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10876:          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  10877:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  10878:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  10879:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10880:          break;
                   10881:        }
                   10882:       }
                   10883:       if(match == 0){
1.338     brouard  10884:        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]);
                   10885:        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  10886:       return 1;
                   10887:       }
                   10888:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10889:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10890:       match=0;
1.342     brouard  10891:       /* printf("Decoderesult very first Product Tvardk[k1=%d][1]=%d Tvardk[k1=%d][2]=%d V%d * V%d\n",k1,Tvardk[k1][1],k1,Tvardk[k1][2],Tvardk[k1][1],Tvardk[k1][2]); */
1.332     brouard  10892:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10893:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10894:          /* modelresult[k2]=k1; */
1.342     brouard  10895:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  10896:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10897:        }
                   10898:       }
                   10899:       if(match == 0){
1.338     brouard  10900:        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);
                   10901:        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  10902:        return 1;
                   10903:       }
                   10904:       match=0;
                   10905:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10906:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10907:          /* modelresult[k2]=k1;*/
1.342     brouard  10908:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  10909:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10910:          break;
                   10911:        }
                   10912:       }
                   10913:       if(match == 0){
1.338     brouard  10914:        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);
                   10915:        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  10916:        return 1;
                   10917:       }
                   10918:     }/* End of testing */
1.333     brouard  10919:   }/* End loop cptcovt */
1.235     brouard  10920:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10921:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10922:   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)
                   10923:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10924:     match=0;
1.318     brouard  10925:     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  10926:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10927:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10928:          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  10929:          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  10930:          ++match;
                   10931:        }
                   10932:       }
                   10933:     }
                   10934:     if(match == 0){
1.338     brouard  10935:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10936:       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  10937:       return 1;
1.234     brouard  10938:     }else if(match > 1){
1.338     brouard  10939:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10940:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10941:       return 1;
1.234     brouard  10942:     }
                   10943:   }
1.334     brouard  10944:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10945:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10946:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10947:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10948:   /* 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*/
                   10949:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10950:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10951:   /*    1 0 0 0 */
                   10952:   /*    2 1 0 0 */
                   10953:   /*    3 0 1 0 */ 
1.330     brouard  10954:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10955:   /*    5 0 0 1 */
1.330     brouard  10956:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10957:   /*    7 0 1 1 */
                   10958:   /*    8 1 1 1 */
1.237     brouard  10959:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10960:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10961:   /* V5*age V5 known which value for nres?  */
                   10962:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10963:   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.
                   10964:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10965:     /* k counting number of combination of single dummies in the equation model */
                   10966:     /* k4 counting single dummies in the equation model */
                   10967:     /* k4q counting single quantitatives in the equation model */
1.344   ! brouard  10968:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
1.334     brouard  10969:        /* 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  10970:       /* 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  10971:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10972:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10973:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10974:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10975:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10976:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10977:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10978:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10979:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10980:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10981:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10982:       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  10983:       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  10984:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10985:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10986:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10987:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10988:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10989:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10990:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10991:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  10992:       /* 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  10993:       k4++;;
1.331     brouard  10994:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10995:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10996:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10997:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10998:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10999:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11000:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11001:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11002:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11003:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11004:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11005:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11006:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11007:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11008:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11009:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11010:       /* 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  11011:       k4q++;;
1.331     brouard  11012:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   11013:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  11014:       /* Wrong we want the value of variable name Tvar[k1] */
                   11015:       
                   11016:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  11017:       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  11018:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  11019:       precov[nres][k1]=Tvalsel[k3];
1.342     brouard  11020:       /* 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  11021:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  11022:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  11023:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11024:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  11025:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11026:       /* 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  11027:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  11028:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11029:       /* 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  11030:     }else{
1.332     brouard  11031:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11032:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11033:     }
                   11034:   }
1.234     brouard  11035:   
1.334     brouard  11036:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11037:   return (0);
                   11038: }
1.235     brouard  11039: 
1.230     brouard  11040: int decodemodel( char model[], int lastobs)
                   11041:  /**< This routine decodes the model and returns:
1.224     brouard  11042:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11043:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11044:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11045:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11046:        * - cptcovage number of covariates with age*products =2
                   11047:        * - cptcovs number of simple covariates
1.339     brouard  11048:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11049:        * - 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  11050:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11051:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11052:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11053:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11054:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11055:        */
1.319     brouard  11056: /* 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  11057: {
1.238     brouard  11058:   int i, j, k, ks, v;
1.227     brouard  11059:   int  j1, k1, k2, k3, k4;
1.136     brouard  11060:   char modelsav[80];
1.145     brouard  11061:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  11062:   char *strpt;
1.136     brouard  11063: 
1.145     brouard  11064:   /*removespace(model);*/
1.136     brouard  11065:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  11066:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11067:     if (strstr(model,"AGE") !=0){
1.192     brouard  11068:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11069:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11070:       return 1;
                   11071:     }
1.141     brouard  11072:     if (strstr(model,"v") !=0){
1.338     brouard  11073:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11074:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11075:       return 1;
                   11076:     }
1.187     brouard  11077:     strcpy(modelsav,model); 
                   11078:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11079:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11080:       if(strpt != model){
1.338     brouard  11081:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11082:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11083:  corresponding column of parameters.\n",model);
1.338     brouard  11084:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11085:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11086:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11087:        return 1;
1.225     brouard  11088:       }
1.187     brouard  11089:       nagesqr=1;
                   11090:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11091:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11092:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11093:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11094:       else 
1.234     brouard  11095:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11096:     }else
                   11097:       nagesqr=0;
                   11098:     if (strlen(modelsav) >1){
                   11099:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11100:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  11101:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  11102:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11103:                     * cst, age and age*age 
                   11104:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11105:       /* including age products which are counted in cptcovage.
                   11106:        * but the covariates which are products must be treated 
                   11107:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  11108:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   11109:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  11110:       
                   11111:       
1.187     brouard  11112:       /*   Design
                   11113:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11114:        *  <          ncovcol=8                >
                   11115:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11116:        *   k=  1    2      3       4     5       6      7        8
                   11117:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   11118:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  11119:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11120:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11121:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11122:        *  Tage[++cptcovage]=k
                   11123:        *       if products, new covar are created after ncovcol with k1
                   11124:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11125:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11126:        *  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
                   11127:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11128:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11129:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   11130:        *  <          ncovcol=8                >
                   11131:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11132:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   11133:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  11134:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  11135:        * p Tprod[1]@2={                         6, 5}
                   11136:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11137:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11138:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11139:        *How to reorganize? Tvars(orted)
1.187     brouard  11140:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11141:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11142:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11143:        * Struct []
                   11144:        */
1.225     brouard  11145:       
1.187     brouard  11146:       /* This loop fills the array Tvar from the string 'model'.*/
                   11147:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11148:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11149:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11150:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11151:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11152:       /*       k=1 Tvar[1]=2 (from V2) */
                   11153:       /*       k=5 Tvar[5] */
                   11154:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11155:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11156:       /*       } */
1.198     brouard  11157:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11158:       /*
                   11159:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11160:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11161:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11162:       }
1.187     brouard  11163:       cptcovage=0;
1.319     brouard  11164:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11165:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11166:                                         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" */
                   11167:        if (nbocc(modelsav,'+')==0)
                   11168:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11169:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11170:        /*scanf("%d",i);*/
1.319     brouard  11171:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   11172:          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  11173:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   11174:            /* covar is not filled and then is empty */
                   11175:            cptcovprod--;
                   11176:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  11177:            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  11178:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  11179:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11180:            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  11181:            /*printf("stre=%s ", stre);*/
                   11182:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   11183:            cptcovprod--;
                   11184:            cutl(stre,strb,strc,'V');
                   11185:            Tvar[k]=atoi(stre);
                   11186:            Typevar[k]=1;  /* 1 for age product */
                   11187:            cptcovage++;
                   11188:            Tage[cptcovage]=k;
                   11189:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11190:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11191:            cptcovn++;
                   11192:            cptcovprodnoage++;k1++;
                   11193:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11194:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11195:                                                because this model-covariate is a construction we invent a new column
                   11196:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11197:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11198:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11199:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11200:            /* Please remark that the new variables are model dependent */
                   11201:            /* If we have 4 variable but the model uses only 3, like in
                   11202:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11203:             *  k=     1     2       3   4     5        6        7       8
                   11204:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11205:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11206:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11207:             */
1.339     brouard  11208:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11209:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11210:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11211:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11212:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11213:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11214:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11215:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11216:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11217:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11218:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11219:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11220:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11221:            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 */
                   11222:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11223:              /* Computes the new covariate which is a product of
                   11224:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11225:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11226:              }
                   11227:            } /*End of FixedV */
1.234     brouard  11228:          } /* End age is not in the model */
                   11229:        } /* End if model includes a product */
1.319     brouard  11230:        else { /* not a product */
1.234     brouard  11231:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11232:          /*  scanf("%d",i);*/
                   11233:          cutl(strd,strc,strb,'V');
                   11234:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11235:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11236:          Tvar[k]=atoi(strd);
                   11237:          Typevar[k]=0;  /* 0 for simple covariates */
                   11238:        }
                   11239:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11240:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11241:                                  scanf("%d",i);*/
1.187     brouard  11242:       } /* end of loop + on total covariates */
                   11243:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11244:   } /* end if strlen(model == 0) */
1.136     brouard  11245:   
                   11246:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11247:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11248:   
1.136     brouard  11249:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11250:      printf("cptcovprod=%d ", cptcovprod);
                   11251:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11252:      scanf("%d ",i);*/
                   11253: 
                   11254: 
1.230     brouard  11255: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11256:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11257: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11258:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11259:    k =           1    2   3     4       5       6      7      8        9
                   11260:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11261:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11262:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11263:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11264:          Tmodelind[combination of covar]=k;
1.225     brouard  11265: */  
                   11266: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11267:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11268:   /* 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  11269:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11270:   printf("Model=1+age+%s\n\
1.227     brouard  11271: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11272: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11273: 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  11274:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11275: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11276: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11277: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
1.342     brouard  11278:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11279:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.343     brouard  11280:   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 loop on k from model */
1.234     brouard  11281:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11282:       Fixed[k]= 0;
                   11283:       Dummy[k]= 0;
1.225     brouard  11284:       ncoveff++;
1.232     brouard  11285:       ncovf++;
1.234     brouard  11286:       nsd++;
                   11287:       modell[k].maintype= FTYPE;
                   11288:       TvarsD[nsd]=Tvar[k];
                   11289:       TvarsDind[nsd]=k;
1.330     brouard  11290:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11291:       TvarF[ncovf]=Tvar[k];
                   11292:       TvarFind[ncovf]=k;
                   11293:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11294:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11295:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11296:     }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  11297:       Fixed[k]= 0;
                   11298:       Dummy[k]= 0;
                   11299:       ncoveff++;
                   11300:       ncovf++;
                   11301:       modell[k].maintype= FTYPE;
                   11302:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11303:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11304:       TvarFind[ncovf]=k;
1.230     brouard  11305:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11306:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11307:     }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  11308:       Fixed[k]= 0;
                   11309:       Dummy[k]= 1;
1.230     brouard  11310:       nqfveff++;
1.234     brouard  11311:       modell[k].maintype= FTYPE;
                   11312:       modell[k].subtype= FQ;
                   11313:       nsq++;
1.334     brouard  11314:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11315:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11316:       ncovf++;
1.234     brouard  11317:       TvarF[ncovf]=Tvar[k];
                   11318:       TvarFind[ncovf]=k;
1.231     brouard  11319:       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  11320:       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  11321:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11322:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11323:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11324:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11325:       ncovvt++;
                   11326:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11327:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11328: 
1.227     brouard  11329:       Fixed[k]= 1;
                   11330:       Dummy[k]= 0;
1.225     brouard  11331:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11332:       modell[k].maintype= VTYPE;
                   11333:       modell[k].subtype= VD;
                   11334:       nsd++;
                   11335:       TvarsD[nsd]=Tvar[k];
                   11336:       TvarsDind[nsd]=k;
1.330     brouard  11337:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11338:       ncovv++; /* Only simple time varying variables */
                   11339:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11340:       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  11341:       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 */
                   11342:       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  11343:       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);
                   11344:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11345:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11346:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11347:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11348:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11349:       ncovvt++;
                   11350:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11351:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11352:       
1.234     brouard  11353:       Fixed[k]= 1;
                   11354:       Dummy[k]= 1;
                   11355:       nqtveff++;
                   11356:       modell[k].maintype= VTYPE;
                   11357:       modell[k].subtype= VQ;
                   11358:       ncovv++; /* Only simple time varying variables */
                   11359:       nsq++;
1.334     brouard  11360:       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) */
                   11361:       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  11362:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11363:       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  11364:       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 */
                   11365:       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  11366:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11367:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.342     brouard  11368:       /* 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); */
                   11369:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11370:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11371:       ncova++;
                   11372:       TvarA[ncova]=Tvar[k];
                   11373:       TvarAind[ncova]=k;
1.231     brouard  11374:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11375:        Fixed[k]= 2;
                   11376:        Dummy[k]= 2;
                   11377:        modell[k].maintype= ATYPE;
                   11378:        modell[k].subtype= APFD;
                   11379:        /* ncoveff++; */
1.227     brouard  11380:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11381:        Fixed[k]= 2;
                   11382:        Dummy[k]= 3;
                   11383:        modell[k].maintype= ATYPE;
                   11384:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11385:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11386:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11387:        Fixed[k]= 3;
                   11388:        Dummy[k]= 2;
                   11389:        modell[k].maintype= ATYPE;
                   11390:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11391:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11392:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11393:        Fixed[k]= 3;
                   11394:        Dummy[k]= 3;
                   11395:        modell[k].maintype= ATYPE;
                   11396:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11397:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11398:       }
1.339     brouard  11399:     }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  */
                   11400:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11401:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11402:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11403:       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 */
                   11404:       ncovvt++;
                   11405:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11406:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11407:       ncovvt++;
                   11408:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11409:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11410: 
                   11411: 
                   11412:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11413:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11414:          Fixed[k]= 1;
                   11415:          Dummy[k]= 0;
                   11416:          modell[k].maintype= FTYPE;
                   11417:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11418:          ncovf++; /* Fixed variables without age */
                   11419:          TvarF[ncovf]=Tvar[k];
                   11420:          TvarFind[ncovf]=k;
1.339     brouard  11421:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11422:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11423:          Dummy[k]= 1;
                   11424:          modell[k].maintype= FTYPE;
                   11425:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11426:          ncovf++; /* Varying variables without age */
                   11427:          TvarF[ncovf]=Tvar[k];
                   11428:          TvarFind[ncovf]=k;
1.339     brouard  11429:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11430:          Fixed[k]= 1;
                   11431:          Dummy[k]= 0;
                   11432:          modell[k].maintype= VTYPE;
                   11433:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11434:          ncovv++; /* Varying variables without age */
1.339     brouard  11435:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11436:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11437:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11438:          Fixed[k]= 1;
                   11439:          Dummy[k]= 1;
                   11440:          modell[k].maintype= VTYPE;
                   11441:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11442:          ncovv++; /* Varying variables without age */
                   11443:          TvarV[ncovv]=Tvar[k];
                   11444:          TvarVind[ncovv]=k;
                   11445:        }
1.339     brouard  11446:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11447:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11448:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11449:          Dummy[k]= 1;
                   11450:          modell[k].maintype= FTYPE;
                   11451:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11452:          ncovf++; /* Fixed variables without age */
                   11453:          TvarF[ncovf]=Tvar[k];
                   11454:          TvarFind[ncovf]=k;
1.339     brouard  11455:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11456:          Fixed[k]= 1;
                   11457:          Dummy[k]= 1;
                   11458:          modell[k].maintype= VTYPE;
                   11459:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11460:          ncovv++; /* Varying variables without age */
                   11461:          TvarV[ncovv]=Tvar[k];
                   11462:          TvarVind[ncovv]=k;
1.339     brouard  11463:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11464:          Fixed[k]= 1;
                   11465:          Dummy[k]= 1;
                   11466:          modell[k].maintype= VTYPE;
                   11467:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11468:          ncovv++; /* Varying variables without age */
                   11469:          TvarV[ncovv]=Tvar[k];
                   11470:          TvarVind[ncovv]=k;
                   11471:          ncovv++; /* Varying variables without age */
                   11472:          TvarV[ncovv]=Tvar[k];
                   11473:          TvarVind[ncovv]=k;
                   11474:        }
1.339     brouard  11475:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11476:        if(Tvard[k1][2] <=ncovcol){
                   11477:          Fixed[k]= 1;
                   11478:          Dummy[k]= 1;
                   11479:          modell[k].maintype= VTYPE;
                   11480:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11481:          ncovv++; /* Varying variables without age */
                   11482:          TvarV[ncovv]=Tvar[k];
                   11483:          TvarVind[ncovv]=k;
                   11484:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11485:          Fixed[k]= 1;
                   11486:          Dummy[k]= 1;
                   11487:          modell[k].maintype= VTYPE;
                   11488:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11489:          ncovv++; /* Varying variables without age */
                   11490:          TvarV[ncovv]=Tvar[k];
                   11491:          TvarVind[ncovv]=k;
                   11492:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11493:          Fixed[k]= 1;
                   11494:          Dummy[k]= 0;
                   11495:          modell[k].maintype= VTYPE;
                   11496:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11497:          ncovv++; /* Varying variables without age */
                   11498:          TvarV[ncovv]=Tvar[k];
                   11499:          TvarVind[ncovv]=k;
                   11500:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11501:          Fixed[k]= 1;
                   11502:          Dummy[k]= 1;
                   11503:          modell[k].maintype= VTYPE;
                   11504:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11505:          ncovv++; /* Varying variables without age */
                   11506:          TvarV[ncovv]=Tvar[k];
                   11507:          TvarVind[ncovv]=k;
                   11508:        }
1.339     brouard  11509:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11510:        if(Tvard[k1][2] <=ncovcol){
                   11511:          Fixed[k]= 1;
                   11512:          Dummy[k]= 1;
                   11513:          modell[k].maintype= VTYPE;
                   11514:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11515:          ncovv++; /* Varying variables without age */
                   11516:          TvarV[ncovv]=Tvar[k];
                   11517:          TvarVind[ncovv]=k;
                   11518:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11519:          Fixed[k]= 1;
                   11520:          Dummy[k]= 1;
                   11521:          modell[k].maintype= VTYPE;
                   11522:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11523:          ncovv++; /* Varying variables without age */
                   11524:          TvarV[ncovv]=Tvar[k];
                   11525:          TvarVind[ncovv]=k;
                   11526:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11527:          Fixed[k]= 1;
                   11528:          Dummy[k]= 1;
                   11529:          modell[k].maintype= VTYPE;
                   11530:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11531:          ncovv++; /* Varying variables without age */
                   11532:          TvarV[ncovv]=Tvar[k];
                   11533:          TvarVind[ncovv]=k;
                   11534:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11535:          Fixed[k]= 1;
                   11536:          Dummy[k]= 1;
                   11537:          modell[k].maintype= VTYPE;
                   11538:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11539:          ncovv++; /* Varying variables without age */
                   11540:          TvarV[ncovv]=Tvar[k];
                   11541:          TvarVind[ncovv]=k;
                   11542:        }
1.227     brouard  11543:       }else{
1.240     brouard  11544:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11545:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11546:       } /*end k1*/
1.225     brouard  11547:     }else{
1.226     brouard  11548:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11549:       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  11550:     }
1.342     brouard  11551:     /* 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]); */
                   11552:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  11553:     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]);
                   11554:   }
                   11555:   /* Searching for doublons in the model */
                   11556:   for(k1=1; k1<= cptcovt;k1++){
                   11557:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11558:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11559:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11560:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11561:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11562:            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]);
                   11563:            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  11564:            return(1);
                   11565:          }
                   11566:        }else if (Typevar[k1] ==2){
                   11567:          k3=Tposprod[k1];
                   11568:          k4=Tposprod[k2];
                   11569:          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  11570:            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]]);
                   11571:            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  11572:            return(1);
                   11573:          }
                   11574:        }
1.227     brouard  11575:       }
                   11576:     }
1.225     brouard  11577:   }
                   11578:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11579:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11580:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11581:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11582:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11583:   /*endread:*/
1.225     brouard  11584:   printf("Exiting decodemodel: ");
                   11585:   return (1);
1.136     brouard  11586: }
                   11587: 
1.169     brouard  11588: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11589: {/* Check ages at death */
1.136     brouard  11590:   int i, m;
1.218     brouard  11591:   int firstone=0;
                   11592:   
1.136     brouard  11593:   for (i=1; i<=imx; i++) {
                   11594:     for(m=2; (m<= maxwav); m++) {
                   11595:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11596:        anint[m][i]=9999;
1.216     brouard  11597:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11598:          s[m][i]=-1;
1.136     brouard  11599:       }
                   11600:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11601:        *nberr = *nberr + 1;
1.218     brouard  11602:        if(firstone == 0){
                   11603:          firstone=1;
1.260     brouard  11604:        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  11605:        }
1.262     brouard  11606:        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  11607:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11608:       }
                   11609:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11610:        (*nberr)++;
1.259     brouard  11611:        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  11612:        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  11613:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11614:       }
                   11615:     }
                   11616:   }
                   11617: 
                   11618:   for (i=1; i<=imx; i++)  {
                   11619:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11620:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11621:       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  11622:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11623:          if(agedc[i]>0){
                   11624:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11625:              agev[m][i]=agedc[i];
1.214     brouard  11626:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11627:            }else {
1.136     brouard  11628:              if ((int)andc[i]!=9999){
                   11629:                nbwarn++;
                   11630:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11631:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11632:                agev[m][i]=-1;
                   11633:              }
                   11634:            }
1.169     brouard  11635:          } /* agedc > 0 */
1.214     brouard  11636:        } /* end if */
1.136     brouard  11637:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11638:                                 years but with the precision of a month */
                   11639:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11640:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11641:            agev[m][i]=1;
                   11642:          else if(agev[m][i] < *agemin){ 
                   11643:            *agemin=agev[m][i];
                   11644:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11645:          }
                   11646:          else if(agev[m][i] >*agemax){
                   11647:            *agemax=agev[m][i];
1.156     brouard  11648:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11649:          }
                   11650:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11651:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11652:        } /* en if 9*/
1.136     brouard  11653:        else { /* =9 */
1.214     brouard  11654:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11655:          agev[m][i]=1;
                   11656:          s[m][i]=-1;
                   11657:        }
                   11658:       }
1.214     brouard  11659:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11660:        agev[m][i]=1;
1.214     brouard  11661:       else{
                   11662:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11663:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11664:        agev[m][i]=0;
                   11665:       }
                   11666:     } /* End for lastpass */
                   11667:   }
1.136     brouard  11668:     
                   11669:   for (i=1; i<=imx; i++)  {
                   11670:     for(m=firstpass; (m<=lastpass); m++){
                   11671:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11672:        (*nberr)++;
1.136     brouard  11673:        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);     
                   11674:        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);     
                   11675:        return 1;
                   11676:       }
                   11677:     }
                   11678:   }
                   11679: 
                   11680:   /*for (i=1; i<=imx; i++){
                   11681:   for (m=firstpass; (m<lastpass); m++){
                   11682:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11683: }
                   11684: 
                   11685: }*/
                   11686: 
                   11687: 
1.139     brouard  11688:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11689:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11690: 
                   11691:   return (0);
1.164     brouard  11692:  /* endread:*/
1.136     brouard  11693:     printf("Exiting calandcheckages: ");
                   11694:     return (1);
                   11695: }
                   11696: 
1.172     brouard  11697: #if defined(_MSC_VER)
                   11698: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11699: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11700: //#include "stdafx.h"
                   11701: //#include <stdio.h>
                   11702: //#include <tchar.h>
                   11703: //#include <windows.h>
                   11704: //#include <iostream>
                   11705: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11706: 
                   11707: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11708: 
                   11709: BOOL IsWow64()
                   11710: {
                   11711:        BOOL bIsWow64 = FALSE;
                   11712: 
                   11713:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11714:        //  (HANDLE, PBOOL);
                   11715: 
                   11716:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11717: 
                   11718:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11719:        const char funcName[] = "IsWow64Process";
                   11720:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11721:                GetProcAddress(module, funcName);
                   11722: 
                   11723:        if (NULL != fnIsWow64Process)
                   11724:        {
                   11725:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11726:                        &bIsWow64))
                   11727:                        //throw std::exception("Unknown error");
                   11728:                        printf("Unknown error\n");
                   11729:        }
                   11730:        return bIsWow64 != FALSE;
                   11731: }
                   11732: #endif
1.177     brouard  11733: 
1.191     brouard  11734: void syscompilerinfo(int logged)
1.292     brouard  11735: {
                   11736: #include <stdint.h>
                   11737: 
                   11738:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11739:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11740:    /* /GS /W3 /Gy
                   11741:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11742:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11743:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11744:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11745:    */ 
                   11746:    /* 64 bits */
1.185     brouard  11747:    /*
                   11748:      /GS /W3 /Gy
                   11749:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11750:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11751:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11752:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11753:    /* Optimization are useless and O3 is slower than O2 */
                   11754:    /*
                   11755:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11756:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11757:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11758:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11759:    */
1.186     brouard  11760:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11761:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11762:       /PDB:"visual studio
                   11763:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11764:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11765:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11766:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11767:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11768:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11769:       uiAccess='false'"
                   11770:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11771:       /NOLOGO /TLBID:1
                   11772:    */
1.292     brouard  11773: 
                   11774: 
1.177     brouard  11775: #if defined __INTEL_COMPILER
1.178     brouard  11776: #if defined(__GNUC__)
                   11777:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11778: #endif
1.177     brouard  11779: #elif defined(__GNUC__) 
1.179     brouard  11780: #ifndef  __APPLE__
1.174     brouard  11781: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11782: #endif
1.177     brouard  11783:    struct utsname sysInfo;
1.178     brouard  11784:    int cross = CROSS;
                   11785:    if (cross){
                   11786:           printf("Cross-");
1.191     brouard  11787:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11788:    }
1.174     brouard  11789: #endif
                   11790: 
1.191     brouard  11791:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11792: #if defined(__clang__)
1.191     brouard  11793:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11794: #endif
                   11795: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11796:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11797: #endif
                   11798: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11799:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11800: #endif
                   11801: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11802:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11803: #endif
                   11804: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11805:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11806: #endif
                   11807: #if defined(_MSC_VER)
1.191     brouard  11808:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11809: #endif
                   11810: #if defined(__PGI)
1.191     brouard  11811:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11812: #endif
                   11813: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11814:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11815: #endif
1.191     brouard  11816:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11817:    
1.167     brouard  11818: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11819: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11820:     // Windows (x64 and x86)
1.191     brouard  11821:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11822: #elif __unix__ // all unices, not all compilers
                   11823:     // Unix
1.191     brouard  11824:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11825: #elif __linux__
                   11826:     // linux
1.191     brouard  11827:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11828: #elif __APPLE__
1.174     brouard  11829:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11830:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11831: #endif
                   11832: 
                   11833: /*  __MINGW32__          */
                   11834: /*  __CYGWIN__  */
                   11835: /* __MINGW64__  */
                   11836: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11837: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11838: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11839: /* _WIN64  // Defined for applications for Win64. */
                   11840: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11841: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11842: 
1.167     brouard  11843: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11844:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11845: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11846:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11847: #else
1.191     brouard  11848:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11849: #endif
                   11850: 
1.169     brouard  11851: #if defined(__GNUC__)
                   11852: # if defined(__GNUC_PATCHLEVEL__)
                   11853: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11854:                             + __GNUC_MINOR__ * 100 \
                   11855:                             + __GNUC_PATCHLEVEL__)
                   11856: # else
                   11857: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11858:                             + __GNUC_MINOR__ * 100)
                   11859: # endif
1.174     brouard  11860:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11861:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11862: 
                   11863:    if (uname(&sysInfo) != -1) {
                   11864:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11865:         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  11866:    }
                   11867:    else
                   11868:       perror("uname() error");
1.179     brouard  11869:    //#ifndef __INTEL_COMPILER 
                   11870: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11871:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11872:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11873: #endif
1.169     brouard  11874: #endif
1.172     brouard  11875: 
1.286     brouard  11876:    //   void main ()
1.172     brouard  11877:    //   {
1.169     brouard  11878: #if defined(_MSC_VER)
1.174     brouard  11879:    if (IsWow64()){
1.191     brouard  11880:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11881:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11882:    }
                   11883:    else{
1.191     brouard  11884:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11885:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11886:    }
1.172     brouard  11887:    //     printf("\nPress Enter to continue...");
                   11888:    //     getchar();
                   11889:    //   }
                   11890: 
1.169     brouard  11891: #endif
                   11892:    
1.167     brouard  11893: 
1.219     brouard  11894: }
1.136     brouard  11895: 
1.219     brouard  11896: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11897:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11898:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11899:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11900:   /* double ftolpl = 1.e-10; */
1.180     brouard  11901:   double age, agebase, agelim;
1.203     brouard  11902:   double tot;
1.180     brouard  11903: 
1.202     brouard  11904:   strcpy(filerespl,"PL_");
                   11905:   strcat(filerespl,fileresu);
                   11906:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11907:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11908:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11909:   }
1.288     brouard  11910:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11911:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11912:   pstamp(ficrespl);
1.288     brouard  11913:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11914:   fprintf(ficrespl,"#Age ");
                   11915:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11916:   fprintf(ficrespl,"\n");
1.180     brouard  11917:   
1.219     brouard  11918:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11919: 
1.219     brouard  11920:   agebase=ageminpar;
                   11921:   agelim=agemaxpar;
1.180     brouard  11922: 
1.227     brouard  11923:   /* i1=pow(2,ncoveff); */
1.234     brouard  11924:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11925:   if (cptcovn < 1){i1=1;}
1.180     brouard  11926: 
1.337     brouard  11927:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11928:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11929:       k=TKresult[nres];
1.338     brouard  11930:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11931:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11932:       /*       continue; */
1.235     brouard  11933: 
1.238     brouard  11934:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11935:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11936:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11937:       /* k=k+1; */
                   11938:       /* to clean */
1.332     brouard  11939:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11940:       fprintf(ficrespl,"#******");
                   11941:       printf("#******");
                   11942:       fprintf(ficlog,"#******");
1.337     brouard  11943:       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  11944:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11945:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11946:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11947:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11948:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11949:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11950:       }
                   11951:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11952:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11953:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11954:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11955:       /* } */
1.238     brouard  11956:       fprintf(ficrespl,"******\n");
                   11957:       printf("******\n");
                   11958:       fprintf(ficlog,"******\n");
                   11959:       if(invalidvarcomb[k]){
                   11960:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11961:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11962:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11963:        continue;
                   11964:       }
1.219     brouard  11965: 
1.238     brouard  11966:       fprintf(ficrespl,"#Age ");
1.337     brouard  11967:       /* for(j=1;j<=cptcoveff;j++) { */
                   11968:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11969:       /* } */
                   11970:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   11971:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11972:       }
                   11973:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11974:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11975:     
1.238     brouard  11976:       for (age=agebase; age<=agelim; age++){
                   11977:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  11978:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   11979:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  11980:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  11981:        /* for(j=1;j<=cptcoveff;j++) */
                   11982:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11983:        for(j=1;j<=cptcovs;j++)
                   11984:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11985:        tot=0.;
                   11986:        for(i=1; i<=nlstate;i++){
                   11987:          tot +=  prlim[i][i];
                   11988:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11989:        }
                   11990:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11991:       } /* Age */
                   11992:       /* was end of cptcod */
1.337     brouard  11993:     } /* nres */
                   11994:   /* } /\* for each combination *\/ */
1.219     brouard  11995:   return 0;
1.180     brouard  11996: }
                   11997: 
1.218     brouard  11998: 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  11999:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12000:        
                   12001:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12002:    * at any age between ageminpar and agemaxpar
                   12003:         */
1.235     brouard  12004:   int i, j, k, i1, nres=0 ;
1.217     brouard  12005:   /* double ftolpl = 1.e-10; */
                   12006:   double age, agebase, agelim;
                   12007:   double tot;
1.218     brouard  12008:   /* double ***mobaverage; */
                   12009:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12010: 
                   12011:   strcpy(fileresplb,"PLB_");
                   12012:   strcat(fileresplb,fileresu);
                   12013:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12014:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12015:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12016:   }
1.288     brouard  12017:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12018:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12019:   pstamp(ficresplb);
1.288     brouard  12020:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12021:   fprintf(ficresplb,"#Age ");
                   12022:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12023:   fprintf(ficresplb,"\n");
                   12024:   
1.218     brouard  12025:   
                   12026:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12027:   
                   12028:   agebase=ageminpar;
                   12029:   agelim=agemaxpar;
                   12030:   
                   12031:   
1.227     brouard  12032:   i1=pow(2,cptcoveff);
1.218     brouard  12033:   if (cptcovn < 1){i1=1;}
1.227     brouard  12034:   
1.238     brouard  12035:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12036:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12037:       k=TKresult[nres];
                   12038:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12039:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12040:      /*        continue; */
                   12041:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12042:       fprintf(ficresplb,"#******");
                   12043:       printf("#******");
                   12044:       fprintf(ficlog,"#******");
1.338     brouard  12045:       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) */
                   12046:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12047:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12048:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12049:       }
1.338     brouard  12050:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12051:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12052:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12053:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12054:       /* } */
                   12055:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12056:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12057:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12058:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12059:       /* } */
1.238     brouard  12060:       fprintf(ficresplb,"******\n");
                   12061:       printf("******\n");
                   12062:       fprintf(ficlog,"******\n");
                   12063:       if(invalidvarcomb[k]){
                   12064:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12065:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12066:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12067:        continue;
                   12068:       }
1.218     brouard  12069:     
1.238     brouard  12070:       fprintf(ficresplb,"#Age ");
1.338     brouard  12071:       for(j=1;j<=cptcovs;j++) {
                   12072:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12073:       }
                   12074:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12075:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12076:     
                   12077:     
1.238     brouard  12078:       for (age=agebase; age<=agelim; age++){
                   12079:        /* for (age=agebase; age<=agebase; age++){ */
                   12080:        if(mobilavproj > 0){
                   12081:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12082:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12083:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12084:        }else if (mobilavproj == 0){
                   12085:          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);
                   12086:          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);
                   12087:          exit(1);
                   12088:        }else{
                   12089:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12090:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12091:          /* printf("TOTOT\n"); */
                   12092:           /* exit(1); */
1.238     brouard  12093:        }
                   12094:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12095:        for(j=1;j<=cptcovs;j++)
                   12096:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12097:        tot=0.;
                   12098:        for(i=1; i<=nlstate;i++){
                   12099:          tot +=  bprlim[i][i];
                   12100:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12101:        }
                   12102:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12103:       } /* Age */
                   12104:       /* was end of cptcod */
1.255     brouard  12105:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12106:     /* } /\* end of any combination *\/ */
1.238     brouard  12107:   } /* end of nres */  
1.218     brouard  12108:   /* hBijx(p, bage, fage); */
                   12109:   /* fclose(ficrespijb); */
                   12110:   
                   12111:   return 0;
1.217     brouard  12112: }
1.218     brouard  12113:  
1.180     brouard  12114: int hPijx(double *p, int bage, int fage){
                   12115:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12116:   /* to be optimized with precov */
1.180     brouard  12117:   int stepsize;
                   12118:   int agelim;
                   12119:   int hstepm;
                   12120:   int nhstepm;
1.235     brouard  12121:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12122: 
                   12123:   double agedeb;
                   12124:   double ***p3mat;
                   12125: 
1.337     brouard  12126:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12127:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12128:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12129:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12130:   }
                   12131:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12132:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12133:   
                   12134:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12135:   /*if (stepm<=24) stepsize=2;*/
                   12136:   
                   12137:   agelim=AGESUP;
                   12138:   hstepm=stepsize*YEARM; /* Every year of age */
                   12139:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12140:   
                   12141:   /* hstepm=1;   aff par mois*/
                   12142:   pstamp(ficrespij);
                   12143:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12144:   i1= pow(2,cptcoveff);
                   12145:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12146:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12147:   /*   k=k+1;  */
                   12148:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12149:     k=TKresult[nres];
1.338     brouard  12150:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12151:     /* for(k=1; k<=i1;k++){ */
                   12152:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12153:     /*         continue; */
                   12154:     fprintf(ficrespij,"\n#****** ");
                   12155:     for(j=1;j<=cptcovs;j++){
                   12156:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12157:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12158:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12159:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12160:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12161:     }
                   12162:     fprintf(ficrespij,"******\n");
                   12163:     
                   12164:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12165:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12166:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12167:       
                   12168:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12169:       
                   12170:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12171:       oldm=oldms;savm=savms;
                   12172:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12173:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12174:       for(i=1; i<=nlstate;i++)
                   12175:        for(j=1; j<=nlstate+ndeath;j++)
                   12176:          fprintf(ficrespij," %1d-%1d",i,j);
                   12177:       fprintf(ficrespij,"\n");
                   12178:       for (h=0; h<=nhstepm; h++){
                   12179:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12180:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12181:        for(i=1; i<=nlstate;i++)
                   12182:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12183:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12184:        fprintf(ficrespij,"\n");
                   12185:       }
1.337     brouard  12186:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12187:       fprintf(ficrespij,"\n");
1.180     brouard  12188:     }
1.337     brouard  12189:   }
                   12190:   /*}*/
                   12191:   return 0;
1.180     brouard  12192: }
1.218     brouard  12193:  
                   12194:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12195:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12196:     /* To be optimized with precov */
1.217     brouard  12197:   int stepsize;
1.218     brouard  12198:   /* int agelim; */
                   12199:        int ageminl;
1.217     brouard  12200:   int hstepm;
                   12201:   int nhstepm;
1.238     brouard  12202:   int h, i, i1, j, k, nres;
1.218     brouard  12203:        
1.217     brouard  12204:   double agedeb;
                   12205:   double ***p3mat;
1.218     brouard  12206:        
                   12207:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12208:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12209:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12210:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12211:   }
                   12212:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12213:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12214:   
                   12215:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12216:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12217:   
1.218     brouard  12218:   /* agelim=AGESUP; */
1.289     brouard  12219:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12220:   hstepm=stepsize*YEARM; /* Every year of age */
                   12221:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12222:   
                   12223:   /* hstepm=1;   aff par mois*/
                   12224:   pstamp(ficrespijb);
1.255     brouard  12225:   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  12226:   i1= pow(2,cptcoveff);
1.218     brouard  12227:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12228:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12229:   /*   k=k+1;  */
1.238     brouard  12230:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12231:     k=TKresult[nres];
1.338     brouard  12232:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12233:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12234:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12235:     /*         continue; */
                   12236:     fprintf(ficrespijb,"\n#****** ");
                   12237:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12238:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12239:       /* for(j=1;j<=cptcoveff;j++) */
                   12240:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12241:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12242:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12243:     }
                   12244:     fprintf(ficrespijb,"******\n");
                   12245:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12246:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12247:       continue;
                   12248:     }
                   12249:     
                   12250:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12251:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12252:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12253:       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 */
                   12254:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12255:       
                   12256:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12257:       
                   12258:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12259:       /* and memory limitations if stepm is small */
                   12260:       
                   12261:       /* oldm=oldms;savm=savms; */
                   12262:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12263:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12264:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12265:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12266:       for(i=1; i<=nlstate;i++)
                   12267:        for(j=1; j<=nlstate+ndeath;j++)
                   12268:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12269:       fprintf(ficrespijb,"\n");
                   12270:       for (h=0; h<=nhstepm; h++){
                   12271:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12272:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12273:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12274:        for(i=1; i<=nlstate;i++)
                   12275:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12276:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12277:        fprintf(ficrespijb,"\n");
1.337     brouard  12278:       }
                   12279:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12280:       fprintf(ficrespijb,"\n");
                   12281:     } /* end age deb */
                   12282:     /* } /\* end combination *\/ */
1.238     brouard  12283:   } /* end nres */
1.218     brouard  12284:   return 0;
                   12285:  } /*  hBijx */
1.217     brouard  12286: 
1.180     brouard  12287: 
1.136     brouard  12288: /***********************************************/
                   12289: /**************** Main Program *****************/
                   12290: /***********************************************/
                   12291: 
                   12292: int main(int argc, char *argv[])
                   12293: {
                   12294: #ifdef GSL
                   12295:   const gsl_multimin_fminimizer_type *T;
                   12296:   size_t iteri = 0, it;
                   12297:   int rval = GSL_CONTINUE;
                   12298:   int status = GSL_SUCCESS;
                   12299:   double ssval;
                   12300: #endif
                   12301:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12302:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12303:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12304:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12305:   int jj, ll, li, lj, lk;
1.136     brouard  12306:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12307:   int num_filled;
1.136     brouard  12308:   int itimes;
                   12309:   int NDIM=2;
                   12310:   int vpopbased=0;
1.235     brouard  12311:   int nres=0;
1.258     brouard  12312:   int endishere=0;
1.277     brouard  12313:   int noffset=0;
1.274     brouard  12314:   int ncurrv=0; /* Temporary variable */
                   12315:   
1.164     brouard  12316:   char ca[32], cb[32];
1.136     brouard  12317:   /*  FILE *fichtm; *//* Html File */
                   12318:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12319:   struct stat info;
1.191     brouard  12320:   double agedeb=0.;
1.194     brouard  12321: 
                   12322:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12323:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12324: 
1.165     brouard  12325:   double fret;
1.191     brouard  12326:   double dum=0.; /* Dummy variable */
1.136     brouard  12327:   double ***p3mat;
1.218     brouard  12328:   /* double ***mobaverage; */
1.319     brouard  12329:   double wald;
1.164     brouard  12330: 
                   12331:   char line[MAXLINE];
1.197     brouard  12332:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12333: 
1.234     brouard  12334:   char  modeltemp[MAXLINE];
1.332     brouard  12335:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12336:   
1.136     brouard  12337:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12338:   char *tok, *val; /* pathtot */
1.334     brouard  12339:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12340:   int c,  h , cpt, c2;
1.191     brouard  12341:   int jl=0;
                   12342:   int i1, j1, jk, stepsize=0;
1.194     brouard  12343:   int count=0;
                   12344: 
1.164     brouard  12345:   int *tab; 
1.136     brouard  12346:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12347:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12348:   /* double anprojf, mprojf, jprojf; */
                   12349:   /* double jintmean,mintmean,aintmean;   */
                   12350:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12351:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12352:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12353:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12354:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12355:   int mobilav=0,popforecast=0;
1.191     brouard  12356:   int hstepm=0, nhstepm=0;
1.136     brouard  12357:   int agemortsup;
                   12358:   float  sumlpop=0.;
                   12359:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12360:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12361: 
1.191     brouard  12362:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12363:   double ftolpl=FTOL;
                   12364:   double **prlim;
1.217     brouard  12365:   double **bprlim;
1.317     brouard  12366:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12367:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12368:   double ***paramstart; /* Matrix of starting parameter values */
                   12369:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12370:   double **matcov; /* Matrix of covariance */
1.203     brouard  12371:   double **hess; /* Hessian matrix */
1.136     brouard  12372:   double ***delti3; /* Scale */
                   12373:   double *delti; /* Scale */
                   12374:   double ***eij, ***vareij;
                   12375:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12376: 
1.136     brouard  12377:   double *epj, vepp;
1.164     brouard  12378: 
1.273     brouard  12379:   double dateprev1, dateprev2;
1.296     brouard  12380:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12381:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12382: 
1.217     brouard  12383: 
1.136     brouard  12384:   double **ximort;
1.145     brouard  12385:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12386:   int *dcwave;
                   12387: 
1.164     brouard  12388:   char z[1]="c";
1.136     brouard  12389: 
                   12390:   /*char  *strt;*/
                   12391:   char strtend[80];
1.126     brouard  12392: 
1.164     brouard  12393: 
1.126     brouard  12394: /*   setlocale (LC_ALL, ""); */
                   12395: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12396: /*   textdomain (PACKAGE); */
                   12397: /*   setlocale (LC_CTYPE, ""); */
                   12398: /*   setlocale (LC_MESSAGES, ""); */
                   12399: 
                   12400:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12401:   rstart_time = time(NULL);  
                   12402:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12403:   start_time = *localtime(&rstart_time);
1.126     brouard  12404:   curr_time=start_time;
1.157     brouard  12405:   /*tml = *localtime(&start_time.tm_sec);*/
                   12406:   /* strcpy(strstart,asctime(&tml)); */
                   12407:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12408: 
                   12409: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12410: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12411: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12412: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12413: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12414: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12415: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12416: /*   strt=asctime(&tmg); */
                   12417: /*   printf("Time(after) =%s",strstart);  */
                   12418: /*  (void) time (&time_value);
                   12419: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12420: *  tm = *localtime(&time_value);
                   12421: *  strstart=asctime(&tm);
                   12422: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12423: */
                   12424: 
                   12425:   nberr=0; /* Number of errors and warnings */
                   12426:   nbwarn=0;
1.184     brouard  12427: #ifdef WIN32
                   12428:   _getcwd(pathcd, size);
                   12429: #else
1.126     brouard  12430:   getcwd(pathcd, size);
1.184     brouard  12431: #endif
1.191     brouard  12432:   syscompilerinfo(0);
1.196     brouard  12433:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12434:   if(argc <=1){
                   12435:     printf("\nEnter the parameter file name: ");
1.205     brouard  12436:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12437:       printf("ERROR Empty parameter file name\n");
                   12438:       goto end;
                   12439:     }
1.126     brouard  12440:     i=strlen(pathr);
                   12441:     if(pathr[i-1]=='\n')
                   12442:       pathr[i-1]='\0';
1.156     brouard  12443:     i=strlen(pathr);
1.205     brouard  12444:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12445:       pathr[i-1]='\0';
1.205     brouard  12446:     }
                   12447:     i=strlen(pathr);
                   12448:     if( i==0 ){
                   12449:       printf("ERROR Empty parameter file name\n");
                   12450:       goto end;
                   12451:     }
                   12452:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12453:       printf("Pathr |%s|\n",pathr);
                   12454:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12455:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12456:       strcpy (pathtot, val);
                   12457:       if(pathr[0] == '\0') break; /* Dirty */
                   12458:     }
                   12459:   }
1.281     brouard  12460:   else if (argc<=2){
                   12461:     strcpy(pathtot,argv[1]);
                   12462:   }
1.126     brouard  12463:   else{
                   12464:     strcpy(pathtot,argv[1]);
1.281     brouard  12465:     strcpy(z,argv[2]);
                   12466:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12467:   }
                   12468:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12469:   /*cygwin_split_path(pathtot,path,optionfile);
                   12470:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12471:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12472: 
                   12473:   /* Split argv[0], imach program to get pathimach */
                   12474:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12475:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12476:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12477:  /*   strcpy(pathimach,argv[0]); */
                   12478:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12479:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12480:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12481: #ifdef WIN32
                   12482:   _chdir(path); /* Can be a relative path */
                   12483:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12484: #else
1.126     brouard  12485:   chdir(path); /* Can be a relative path */
1.184     brouard  12486:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12487: #endif
                   12488:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12489:   strcpy(command,"mkdir ");
                   12490:   strcat(command,optionfilefiname);
                   12491:   if((outcmd=system(command)) != 0){
1.169     brouard  12492:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12493:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12494:     /* fclose(ficlog); */
                   12495: /*     exit(1); */
                   12496:   }
                   12497: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12498: /*     perror("mkdir"); */
                   12499: /*   } */
                   12500: 
                   12501:   /*-------- arguments in the command line --------*/
                   12502: 
1.186     brouard  12503:   /* Main Log file */
1.126     brouard  12504:   strcat(filelog, optionfilefiname);
                   12505:   strcat(filelog,".log");    /* */
                   12506:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12507:     printf("Problem with logfile %s\n",filelog);
                   12508:     goto end;
                   12509:   }
                   12510:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12511:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12512:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12513:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12514:  path=%s \n\
                   12515:  optionfile=%s\n\
                   12516:  optionfilext=%s\n\
1.156     brouard  12517:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12518: 
1.197     brouard  12519:   syscompilerinfo(1);
1.167     brouard  12520: 
1.126     brouard  12521:   printf("Local time (at start):%s",strstart);
                   12522:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12523:   fflush(ficlog);
                   12524: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12525: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12526: 
                   12527:   /* */
                   12528:   strcpy(fileres,"r");
                   12529:   strcat(fileres, optionfilefiname);
1.201     brouard  12530:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12531:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12532:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12533: 
1.186     brouard  12534:   /* Main ---------arguments file --------*/
1.126     brouard  12535: 
                   12536:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12537:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12538:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12539:     fflush(ficlog);
1.149     brouard  12540:     /* goto end; */
                   12541:     exit(70); 
1.126     brouard  12542:   }
                   12543: 
                   12544:   strcpy(filereso,"o");
1.201     brouard  12545:   strcat(filereso,fileresu);
1.126     brouard  12546:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12547:     printf("Problem with Output resultfile: %s\n", filereso);
                   12548:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12549:     fflush(ficlog);
                   12550:     goto end;
                   12551:   }
1.278     brouard  12552:       /*-------- Rewriting parameter file ----------*/
                   12553:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12554:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12555:   strcat(rfileres,".");    /* */
                   12556:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12557:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12558:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12559:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12560:     fflush(ficlog);
                   12561:     goto end;
                   12562:   }
                   12563:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12564: 
1.278     brouard  12565:                                      
1.126     brouard  12566:   /* Reads comments: lines beginning with '#' */
                   12567:   numlinepar=0;
1.277     brouard  12568:   /* Is it a BOM UTF-8 Windows file? */
                   12569:   /* First parameter line */
1.197     brouard  12570:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12571:     noffset=0;
                   12572:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12573:     {
                   12574:       noffset=noffset+3;
                   12575:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12576:     }
1.302     brouard  12577: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12578:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12579:     {
                   12580:       noffset=noffset+2;
                   12581:       printf("# File is an UTF16BE BOM file\n");
                   12582:     }
                   12583:     else if( line[0] == 0 && line[1] == 0)
                   12584:     {
                   12585:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12586:        noffset=noffset+4;
                   12587:        printf("# File is an UTF16BE BOM file\n");
                   12588:       }
                   12589:     } else{
                   12590:       ;/*printf(" Not a BOM file\n");*/
                   12591:     }
                   12592:   
1.197     brouard  12593:     /* If line starts with a # it is a comment */
1.277     brouard  12594:     if (line[noffset] == '#') {
1.197     brouard  12595:       numlinepar++;
                   12596:       fputs(line,stdout);
                   12597:       fputs(line,ficparo);
1.278     brouard  12598:       fputs(line,ficres);
1.197     brouard  12599:       fputs(line,ficlog);
                   12600:       continue;
                   12601:     }else
                   12602:       break;
                   12603:   }
                   12604:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12605:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12606:     if (num_filled != 5) {
                   12607:       printf("Should be 5 parameters\n");
1.283     brouard  12608:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12609:     }
1.126     brouard  12610:     numlinepar++;
1.197     brouard  12611:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12612:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12613:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12614:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12615:   }
                   12616:   /* Second parameter line */
                   12617:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12618:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12619:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12620:     if (line[0] == '#') {
                   12621:       numlinepar++;
1.283     brouard  12622:       printf("%s",line);
                   12623:       fprintf(ficres,"%s",line);
                   12624:       fprintf(ficparo,"%s",line);
                   12625:       fprintf(ficlog,"%s",line);
1.197     brouard  12626:       continue;
                   12627:     }else
                   12628:       break;
                   12629:   }
1.223     brouard  12630:   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", \
                   12631:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12632:     if (num_filled != 11) {
                   12633:       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  12634:       printf("but line=%s\n",line);
1.283     brouard  12635:       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");
                   12636:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12637:     }
1.286     brouard  12638:     if( lastpass > maxwav){
                   12639:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12640:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12641:       fflush(ficlog);
                   12642:       goto end;
                   12643:     }
                   12644:       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  12645:     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  12646:     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  12647:     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  12648:   }
1.203     brouard  12649:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12650:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12651:   /* Third parameter line */
                   12652:   while(fgets(line, MAXLINE, ficpar)) {
                   12653:     /* If line starts with a # it is a comment */
                   12654:     if (line[0] == '#') {
                   12655:       numlinepar++;
1.283     brouard  12656:       printf("%s",line);
                   12657:       fprintf(ficres,"%s",line);
                   12658:       fprintf(ficparo,"%s",line);
                   12659:       fprintf(ficlog,"%s",line);
1.197     brouard  12660:       continue;
                   12661:     }else
                   12662:       break;
                   12663:   }
1.201     brouard  12664:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12665:     if (num_filled != 1){
1.302     brouard  12666:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12667:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12668:       model[0]='\0';
                   12669:       goto end;
                   12670:     }
                   12671:     else{
                   12672:       if (model[0]=='+'){
                   12673:        for(i=1; i<=strlen(model);i++)
                   12674:          modeltemp[i-1]=model[i];
1.201     brouard  12675:        strcpy(model,modeltemp); 
1.197     brouard  12676:       }
                   12677:     }
1.338     brouard  12678:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12679:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12680:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12681:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12682:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12683:   }
                   12684:   /* 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); */
                   12685:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12686:   /* 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  12687:   /* 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); */
                   12688:   /* 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  12689:   fflush(ficlog);
1.190     brouard  12690:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12691:   if(model[0]=='#'){
1.279     brouard  12692:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12693:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12694:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12695:     if(mle != -1){
1.279     brouard  12696:       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  12697:       exit(1);
                   12698:     }
                   12699:   }
1.126     brouard  12700:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12701:     ungetc(c,ficpar);
                   12702:     fgets(line, MAXLINE, ficpar);
                   12703:     numlinepar++;
1.195     brouard  12704:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12705:       z[0]=line[1];
1.342     brouard  12706:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  12707:       debugILK=1;printf("DebugILK\n");
1.195     brouard  12708:     }
                   12709:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12710:     fputs(line, stdout);
                   12711:     //puts(line);
1.126     brouard  12712:     fputs(line,ficparo);
                   12713:     fputs(line,ficlog);
                   12714:   }
                   12715:   ungetc(c,ficpar);
                   12716: 
                   12717:    
1.290     brouard  12718:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12719:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12720:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  12721:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   12722:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12723:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12724:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12725:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12726:   */
                   12727:   if (strlen(model)>1) 
1.187     brouard  12728:     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  12729:   else
1.187     brouard  12730:     ncovmodel=2; /* Constant and age */
1.133     brouard  12731:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12732:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12733:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12734:     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);
                   12735:     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);
                   12736:     fflush(stdout);
                   12737:     fclose (ficlog);
                   12738:     goto end;
                   12739:   }
1.126     brouard  12740:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12741:   delti=delti3[1][1];
                   12742:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12743:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12744: /* We could also provide initial parameters values giving by simple logistic regression 
                   12745:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12746:       /* for(i=1;i<nlstate;i++){ */
                   12747:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12748:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12749:       /* } */
1.126     brouard  12750:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12751:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12752:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12753:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12754:     fclose (ficparo);
                   12755:     fclose (ficlog);
                   12756:     goto end;
                   12757:     exit(0);
1.220     brouard  12758:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12759:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12760:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12761:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12762:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12763:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12764:     hess=matrix(1,npar,1,npar);
1.220     brouard  12765:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12766:     /* Read guessed parameters */
1.126     brouard  12767:     /* Reads comments: lines beginning with '#' */
                   12768:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12769:       ungetc(c,ficpar);
                   12770:       fgets(line, MAXLINE, ficpar);
                   12771:       numlinepar++;
1.141     brouard  12772:       fputs(line,stdout);
1.126     brouard  12773:       fputs(line,ficparo);
                   12774:       fputs(line,ficlog);
                   12775:     }
                   12776:     ungetc(c,ficpar);
                   12777:     
                   12778:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12779:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12780:     for(i=1; i <=nlstate; i++){
1.234     brouard  12781:       j=0;
1.126     brouard  12782:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12783:        if(jj==i) continue;
                   12784:        j++;
1.292     brouard  12785:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12786:          ungetc(c,ficpar);
                   12787:          fgets(line, MAXLINE, ficpar);
                   12788:          numlinepar++;
                   12789:          fputs(line,stdout);
                   12790:          fputs(line,ficparo);
                   12791:          fputs(line,ficlog);
                   12792:        }
                   12793:        ungetc(c,ficpar);
1.234     brouard  12794:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12795:        if ((i1 != i) || (j1 != jj)){
                   12796:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12797: It might be a problem of design; if ncovcol and the model are correct\n \
                   12798: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12799:          exit(1);
                   12800:        }
                   12801:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12802:        if(mle==1)
                   12803:          printf("%1d%1d",i,jj);
                   12804:        fprintf(ficlog,"%1d%1d",i,jj);
                   12805:        for(k=1; k<=ncovmodel;k++){
                   12806:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12807:          if(mle==1){
                   12808:            printf(" %lf",param[i][j][k]);
                   12809:            fprintf(ficlog," %lf",param[i][j][k]);
                   12810:          }
                   12811:          else
                   12812:            fprintf(ficlog," %lf",param[i][j][k]);
                   12813:          fprintf(ficparo," %lf",param[i][j][k]);
                   12814:        }
                   12815:        fscanf(ficpar,"\n");
                   12816:        numlinepar++;
                   12817:        if(mle==1)
                   12818:          printf("\n");
                   12819:        fprintf(ficlog,"\n");
                   12820:        fprintf(ficparo,"\n");
1.126     brouard  12821:       }
                   12822:     }  
                   12823:     fflush(ficlog);
1.234     brouard  12824:     
1.251     brouard  12825:     /* Reads parameters values */
1.126     brouard  12826:     p=param[1][1];
1.251     brouard  12827:     pstart=paramstart[1][1];
1.126     brouard  12828:     
                   12829:     /* Reads comments: lines beginning with '#' */
                   12830:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12831:       ungetc(c,ficpar);
                   12832:       fgets(line, MAXLINE, ficpar);
                   12833:       numlinepar++;
1.141     brouard  12834:       fputs(line,stdout);
1.126     brouard  12835:       fputs(line,ficparo);
                   12836:       fputs(line,ficlog);
                   12837:     }
                   12838:     ungetc(c,ficpar);
                   12839: 
                   12840:     for(i=1; i <=nlstate; i++){
                   12841:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12842:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12843:        if ( (i1-i) * (j1-j) != 0){
                   12844:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12845:          exit(1);
                   12846:        }
                   12847:        printf("%1d%1d",i,j);
                   12848:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12849:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12850:        for(k=1; k<=ncovmodel;k++){
                   12851:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12852:          printf(" %le",delti3[i][j][k]);
                   12853:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12854:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12855:        }
                   12856:        fscanf(ficpar,"\n");
                   12857:        numlinepar++;
                   12858:        printf("\n");
                   12859:        fprintf(ficparo,"\n");
                   12860:        fprintf(ficlog,"\n");
1.126     brouard  12861:       }
                   12862:     }
                   12863:     fflush(ficlog);
1.234     brouard  12864:     
1.145     brouard  12865:     /* Reads covariance matrix */
1.126     brouard  12866:     delti=delti3[1][1];
1.220     brouard  12867:                
                   12868:                
1.126     brouard  12869:     /* 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  12870:                
1.126     brouard  12871:     /* Reads comments: lines beginning with '#' */
                   12872:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12873:       ungetc(c,ficpar);
                   12874:       fgets(line, MAXLINE, ficpar);
                   12875:       numlinepar++;
1.141     brouard  12876:       fputs(line,stdout);
1.126     brouard  12877:       fputs(line,ficparo);
                   12878:       fputs(line,ficlog);
                   12879:     }
                   12880:     ungetc(c,ficpar);
1.220     brouard  12881:                
1.126     brouard  12882:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12883:     hess=matrix(1,npar,1,npar);
1.131     brouard  12884:     for(i=1; i <=npar; i++)
                   12885:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12886:                
1.194     brouard  12887:     /* Scans npar lines */
1.126     brouard  12888:     for(i=1; i <=npar; i++){
1.226     brouard  12889:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12890:       if(count != 3){
1.226     brouard  12891:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12892: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12893: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12894:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12895: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12896: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12897:        exit(1);
1.220     brouard  12898:       }else{
1.226     brouard  12899:        if(mle==1)
                   12900:          printf("%1d%1d%d",i1,j1,jk);
                   12901:       }
                   12902:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12903:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12904:       for(j=1; j <=i; j++){
1.226     brouard  12905:        fscanf(ficpar," %le",&matcov[i][j]);
                   12906:        if(mle==1){
                   12907:          printf(" %.5le",matcov[i][j]);
                   12908:        }
                   12909:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12910:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12911:       }
                   12912:       fscanf(ficpar,"\n");
                   12913:       numlinepar++;
                   12914:       if(mle==1)
1.220     brouard  12915:                                printf("\n");
1.126     brouard  12916:       fprintf(ficlog,"\n");
                   12917:       fprintf(ficparo,"\n");
                   12918:     }
1.194     brouard  12919:     /* End of read covariance matrix npar lines */
1.126     brouard  12920:     for(i=1; i <=npar; i++)
                   12921:       for(j=i+1;j<=npar;j++)
1.226     brouard  12922:        matcov[i][j]=matcov[j][i];
1.126     brouard  12923:     
                   12924:     if(mle==1)
                   12925:       printf("\n");
                   12926:     fprintf(ficlog,"\n");
                   12927:     
                   12928:     fflush(ficlog);
                   12929:     
                   12930:   }    /* End of mle != -3 */
1.218     brouard  12931:   
1.186     brouard  12932:   /*  Main data
                   12933:    */
1.290     brouard  12934:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12935:   /* num=lvector(1,n); */
                   12936:   /* moisnais=vector(1,n); */
                   12937:   /* annais=vector(1,n); */
                   12938:   /* moisdc=vector(1,n); */
                   12939:   /* andc=vector(1,n); */
                   12940:   /* weight=vector(1,n); */
                   12941:   /* agedc=vector(1,n); */
                   12942:   /* cod=ivector(1,n); */
                   12943:   /* for(i=1;i<=n;i++){ */
                   12944:   num=lvector(firstobs,lastobs);
                   12945:   moisnais=vector(firstobs,lastobs);
                   12946:   annais=vector(firstobs,lastobs);
                   12947:   moisdc=vector(firstobs,lastobs);
                   12948:   andc=vector(firstobs,lastobs);
                   12949:   weight=vector(firstobs,lastobs);
                   12950:   agedc=vector(firstobs,lastobs);
                   12951:   cod=ivector(firstobs,lastobs);
                   12952:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12953:     num[i]=0;
                   12954:     moisnais[i]=0;
                   12955:     annais[i]=0;
                   12956:     moisdc[i]=0;
                   12957:     andc[i]=0;
                   12958:     agedc[i]=0;
                   12959:     cod[i]=0;
                   12960:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12961:   }
1.290     brouard  12962:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12963:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12964:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12965:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12966:   tab=ivector(1,NCOVMAX);
1.144     brouard  12967:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12968:   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  12969: 
1.136     brouard  12970:   /* Reads data from file datafile */
                   12971:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12972:     goto end;
                   12973: 
                   12974:   /* Calculation of the number of parameters from char model */
1.234     brouard  12975:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12976:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12977:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12978:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12979:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12980:   */
                   12981:   
                   12982:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12983:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12984:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12985:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12986:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12987:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12988:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12989:   TvarF=ivector(1,NCOVMAX); /*  */
                   12990:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12991:   TvarV=ivector(1,NCOVMAX); /*  */
                   12992:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12993:   TvarA=ivector(1,NCOVMAX); /*  */
                   12994:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12995:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12996:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12997:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12998:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12999:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13000:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13001:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13002:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13003:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13004:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13005: 
1.230     brouard  13006:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13007:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13008:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13009:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13010:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  13011:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13012:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13013:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13014:   */
                   13015:   /* For model-covariate k tells which data-covariate to use but
                   13016:     because this model-covariate is a construction we invent a new column
                   13017:     ncovcol + k1
                   13018:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13019:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13020:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13021:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13022:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13023:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13024:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13025:   */
1.145     brouard  13026:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13027:   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  13028:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13029:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  13030:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  13031:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13032:                         4 covariates (3 plus signs)
                   13033:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13034:                           */  
                   13035:   for(i=1;i<NCOVMAX;i++)
                   13036:     Tage[i]=0;
1.230     brouard  13037:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13038:                                * individual dummy, fixed or varying:
                   13039:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13040:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13041:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13042:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13043:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13044:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13045:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13046:                                * individual quantitative, fixed or varying:
                   13047:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13048:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13049:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  13050: /* Main decodemodel */
                   13051: 
1.187     brouard  13052: 
1.223     brouard  13053:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13054:     goto end;
                   13055: 
1.137     brouard  13056:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13057:     nbwarn++;
                   13058:     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); 
                   13059:     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); 
                   13060:   }
1.136     brouard  13061:     /*  if(mle==1){*/
1.137     brouard  13062:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13063:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13064:   }
                   13065: 
                   13066:     /*-calculation of age at interview from date of interview and age at death -*/
                   13067:   agev=matrix(1,maxwav,1,imx);
                   13068: 
                   13069:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13070:     goto end;
                   13071: 
1.126     brouard  13072: 
1.136     brouard  13073:   agegomp=(int)agemin;
1.290     brouard  13074:   free_vector(moisnais,firstobs,lastobs);
                   13075:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13076:   /* free_matrix(mint,1,maxwav,1,n);
                   13077:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13078:   /* free_vector(moisdc,1,n); */
                   13079:   /* free_vector(andc,1,n); */
1.145     brouard  13080:   /* */
                   13081:   
1.126     brouard  13082:   wav=ivector(1,imx);
1.214     brouard  13083:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13084:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13085:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13086:   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.*/
                   13087:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13088:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13089:    
                   13090:   /* Concatenates waves */
1.214     brouard  13091:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13092:      Death is a valid wave (if date is known).
                   13093:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13094:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13095:      and mw[mi+1][i]. dh depends on stepm.
                   13096:   */
                   13097: 
1.126     brouard  13098:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13099:   /* Concatenates waves */
1.145     brouard  13100:  
1.290     brouard  13101:   free_vector(moisdc,firstobs,lastobs);
                   13102:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13103: 
1.126     brouard  13104:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13105:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13106:   ncodemax[1]=1;
1.145     brouard  13107:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13108:   cptcoveff=0;
1.220     brouard  13109:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13110:     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  13111:   }
                   13112:   
                   13113:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13114:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13115:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13116:     invalidvarcomb[i]=0;
                   13117:   
1.211     brouard  13118:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13119:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13120:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13121:   
1.200     brouard  13122:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13123:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13124:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13125:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13126:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13127:    * (currently 0 or 1) in the data.
                   13128:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13129:    * corresponding modality (h,j).
                   13130:    */
                   13131: 
1.145     brouard  13132:   h=0;
                   13133:   /*if (cptcovn > 0) */
1.126     brouard  13134:   m=pow(2,cptcoveff);
                   13135:  
1.144     brouard  13136:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13137:           * For k=4 covariates, h goes from 1 to m=2**k
                   13138:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13139:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13140:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13141:           *______________________________   *______________________
                   13142:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13143:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13144:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13145:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13146:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13147:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13148:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13149:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13150:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13151:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13152:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13153:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13154:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13155:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13156:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13157:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13158:           */                                     
1.212     brouard  13159:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13160:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13161:      * and the value of each covariate?
                   13162:      * V1=1, V2=1, V3=2, V4=1 ?
                   13163:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13164:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13165:      * In order to get the real value in the data, we use nbcode
                   13166:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13167:      * We are keeping this crazy system in order to be able (in the future?) 
                   13168:      * to have more than 2 values (0 or 1) for a covariate.
                   13169:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13170:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13171:      *              bbbbbbbb
                   13172:      *              76543210     
                   13173:      *   h-1        00000101 (6-1=5)
1.219     brouard  13174:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13175:      *           &
                   13176:      *     1        00000001 (1)
1.219     brouard  13177:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13178:      *          +1= 00000001 =1 
1.211     brouard  13179:      *
                   13180:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13181:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13182:      *    >>k'            11
                   13183:      *          &   00000001
                   13184:      *            = 00000001
                   13185:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13186:      * Reverse h=6 and m=16?
                   13187:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13188:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13189:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13190:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13191:      * V3=decodtabm(14,3,2**4)=2
                   13192:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13193:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13194:      *          &1 000000001
                   13195:      *           = 000000001
                   13196:      *         +1= 000000010 =2
                   13197:      *                  2211
                   13198:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13199:      *                  V3=2
1.220     brouard  13200:                 * codtabm and decodtabm are identical
1.211     brouard  13201:      */
                   13202: 
1.145     brouard  13203: 
                   13204:  free_ivector(Ndum,-1,NCOVMAX);
                   13205: 
                   13206: 
1.126     brouard  13207:     
1.186     brouard  13208:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13209:   strcpy(optionfilegnuplot,optionfilefiname);
                   13210:   if(mle==-3)
1.201     brouard  13211:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13212:   strcat(optionfilegnuplot,".gp");
                   13213: 
                   13214:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13215:     printf("Problem with file %s",optionfilegnuplot);
                   13216:   }
                   13217:   else{
1.204     brouard  13218:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13219:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13220:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13221:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13222:   }
                   13223:   /*  fclose(ficgp);*/
1.186     brouard  13224: 
                   13225: 
                   13226:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13227: 
                   13228:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13229:   if(mle==-3)
1.201     brouard  13230:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13231:   strcat(optionfilehtm,".htm");
                   13232:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13233:     printf("Problem with %s \n",optionfilehtm);
                   13234:     exit(0);
1.126     brouard  13235:   }
                   13236: 
                   13237:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13238:   strcat(optionfilehtmcov,"-cov.htm");
                   13239:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13240:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13241:   }
                   13242:   else{
                   13243:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13244: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13245: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13246:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13247:   }
                   13248: 
1.335     brouard  13249:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13250: <title>IMaCh %s</title></head>\n\
                   13251:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13252: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13253: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13254: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13255: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13256:   
                   13257:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13258: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13259: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13260: 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  13261: \n\
                   13262: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13263:  <ul><li><h4>Parameter files</h4>\n\
                   13264:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13265:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13266:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13267:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13268:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13269:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13270:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13271:          fileres,fileres,\
                   13272:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13273:   fflush(fichtm);
                   13274: 
                   13275:   strcpy(pathr,path);
                   13276:   strcat(pathr,optionfilefiname);
1.184     brouard  13277: #ifdef WIN32
                   13278:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13279: #else
1.126     brouard  13280:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13281: #endif
                   13282:          
1.126     brouard  13283:   
1.220     brouard  13284:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13285:                 and for any valid combination of covariates
1.126     brouard  13286:      and prints on file fileres'p'. */
1.251     brouard  13287:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13288:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13289: 
                   13290:   fprintf(fichtm,"\n");
1.286     brouard  13291:   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  13292:          ftol, stepm);
                   13293:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13294:   ncurrv=1;
                   13295:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13296:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13297:   ncurrv=i;
                   13298:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13299:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13300:   ncurrv=i;
                   13301:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13302:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13303:   ncurrv=i;
                   13304:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13305:   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", \
                   13306:           nlstate, ndeath, maxwav, mle, weightopt);
                   13307: 
                   13308:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13309: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13310: 
                   13311:   
1.317     brouard  13312:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13313: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13314: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13315:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13316:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13317:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13318:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13319:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13320:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13321: 
1.126     brouard  13322:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13323:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13324:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13325: 
                   13326:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13327:   /* For mortality only */
1.126     brouard  13328:   if (mle==-3){
1.136     brouard  13329:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13330:     for(i=1;i<=NDIM;i++)
                   13331:       for(j=1;j<=NDIM;j++)
                   13332:        ximort[i][j]=0.;
1.186     brouard  13333:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13334:     cens=ivector(firstobs,lastobs);
                   13335:     ageexmed=vector(firstobs,lastobs);
                   13336:     agecens=vector(firstobs,lastobs);
                   13337:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13338:                
1.126     brouard  13339:     for (i=1; i<=imx; i++){
                   13340:       dcwave[i]=-1;
                   13341:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13342:        if (s[m][i]>nlstate) {
                   13343:          dcwave[i]=m;
                   13344:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13345:          break;
                   13346:        }
1.126     brouard  13347:     }
1.226     brouard  13348:     
1.126     brouard  13349:     for (i=1; i<=imx; i++) {
                   13350:       if (wav[i]>0){
1.226     brouard  13351:        ageexmed[i]=agev[mw[1][i]][i];
                   13352:        j=wav[i];
                   13353:        agecens[i]=1.; 
                   13354:        
                   13355:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13356:          agecens[i]=agev[mw[j][i]][i];
                   13357:          cens[i]= 1;
                   13358:        }else if (ageexmed[i]< 1) 
                   13359:          cens[i]= -1;
                   13360:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13361:          cens[i]=0 ;
1.126     brouard  13362:       }
                   13363:       else cens[i]=-1;
                   13364:     }
                   13365:     
                   13366:     for (i=1;i<=NDIM;i++) {
                   13367:       for (j=1;j<=NDIM;j++)
1.226     brouard  13368:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13369:     }
                   13370:     
1.302     brouard  13371:     p[1]=0.0268; p[NDIM]=0.083;
                   13372:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13373:     
                   13374:     
1.136     brouard  13375: #ifdef GSL
                   13376:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13377: #else
1.126     brouard  13378:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13379: #endif
1.201     brouard  13380:     strcpy(filerespow,"POW-MORT_"); 
                   13381:     strcat(filerespow,fileresu);
1.126     brouard  13382:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13383:       printf("Problem with resultfile: %s\n", filerespow);
                   13384:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13385:     }
1.136     brouard  13386: #ifdef GSL
                   13387:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13388: #else
1.126     brouard  13389:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13390: #endif
1.126     brouard  13391:     /*  for (i=1;i<=nlstate;i++)
                   13392:        for(j=1;j<=nlstate+ndeath;j++)
                   13393:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13394:     */
                   13395:     fprintf(ficrespow,"\n");
1.136     brouard  13396: #ifdef GSL
                   13397:     /* gsl starts here */ 
                   13398:     T = gsl_multimin_fminimizer_nmsimplex;
                   13399:     gsl_multimin_fminimizer *sfm = NULL;
                   13400:     gsl_vector *ss, *x;
                   13401:     gsl_multimin_function minex_func;
                   13402: 
                   13403:     /* Initial vertex size vector */
                   13404:     ss = gsl_vector_alloc (NDIM);
                   13405:     
                   13406:     if (ss == NULL){
                   13407:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13408:     }
                   13409:     /* Set all step sizes to 1 */
                   13410:     gsl_vector_set_all (ss, 0.001);
                   13411: 
                   13412:     /* Starting point */
1.126     brouard  13413:     
1.136     brouard  13414:     x = gsl_vector_alloc (NDIM);
                   13415:     
                   13416:     if (x == NULL){
                   13417:       gsl_vector_free(ss);
                   13418:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13419:     }
                   13420:   
                   13421:     /* Initialize method and iterate */
                   13422:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13423:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13424:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13425:     gsl_vector_set(x, 0, p[1]);
                   13426:     gsl_vector_set(x, 1, p[2]);
                   13427: 
                   13428:     minex_func.f = &gompertz_f;
                   13429:     minex_func.n = NDIM;
                   13430:     minex_func.params = (void *)&p; /* ??? */
                   13431:     
                   13432:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13433:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13434:     
                   13435:     printf("Iterations beginning .....\n\n");
                   13436:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13437: 
                   13438:     iteri=0;
                   13439:     while (rval == GSL_CONTINUE){
                   13440:       iteri++;
                   13441:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13442:       
                   13443:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13444:       fflush(0);
                   13445:       
                   13446:       if (status) 
                   13447:         break;
                   13448:       
                   13449:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13450:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13451:       
                   13452:       if (rval == GSL_SUCCESS)
                   13453:         printf ("converged to a local maximum at\n");
                   13454:       
                   13455:       printf("%5d ", iteri);
                   13456:       for (it = 0; it < NDIM; it++){
                   13457:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13458:       }
                   13459:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13460:     }
                   13461:     
                   13462:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13463:     
                   13464:     gsl_vector_free(x); /* initial values */
                   13465:     gsl_vector_free(ss); /* inital step size */
                   13466:     for (it=0; it<NDIM; it++){
                   13467:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13468:       fprintf(ficrespow," %.12lf", p[it]);
                   13469:     }
                   13470:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13471: #endif
                   13472: #ifdef POWELL
                   13473:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13474: #endif  
1.126     brouard  13475:     fclose(ficrespow);
                   13476:     
1.203     brouard  13477:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13478: 
                   13479:     for(i=1; i <=NDIM; i++)
                   13480:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13481:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13482:     
                   13483:     printf("\nCovariance matrix\n ");
1.203     brouard  13484:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13485:     for(i=1; i <=NDIM; i++) {
                   13486:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13487:                                printf("%f ",matcov[i][j]);
                   13488:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13489:       }
1.203     brouard  13490:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13491:     }
                   13492:     
                   13493:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13494:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13495:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13496:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13497:     }
1.302     brouard  13498:     lsurv=vector(agegomp,AGESUP);
                   13499:     lpop=vector(agegomp,AGESUP);
                   13500:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13501:     lsurv[agegomp]=100000;
                   13502:     
                   13503:     for (k=agegomp;k<=AGESUP;k++) {
                   13504:       agemortsup=k;
                   13505:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13506:     }
                   13507:     
                   13508:     for (k=agegomp;k<agemortsup;k++)
                   13509:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13510:     
                   13511:     for (k=agegomp;k<agemortsup;k++){
                   13512:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13513:       sumlpop=sumlpop+lpop[k];
                   13514:     }
                   13515:     
                   13516:     tpop[agegomp]=sumlpop;
                   13517:     for (k=agegomp;k<(agemortsup-3);k++){
                   13518:       /*  tpop[k+1]=2;*/
                   13519:       tpop[k+1]=tpop[k]-lpop[k];
                   13520:     }
                   13521:     
                   13522:     
                   13523:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13524:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13525:       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]);
                   13526:     
                   13527:     
                   13528:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13529:                ageminpar=50;
                   13530:                agemaxpar=100;
1.194     brouard  13531:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13532:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13533: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13534: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13535:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13536: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13537: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13538:     }else{
                   13539:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13540:                        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  13541:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13542:                }
1.201     brouard  13543:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13544:                     stepm, weightopt,\
                   13545:                     model,imx,p,matcov,agemortsup);
                   13546:     
1.302     brouard  13547:     free_vector(lsurv,agegomp,AGESUP);
                   13548:     free_vector(lpop,agegomp,AGESUP);
                   13549:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13550:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13551:     free_ivector(dcwave,firstobs,lastobs);
                   13552:     free_vector(agecens,firstobs,lastobs);
                   13553:     free_vector(ageexmed,firstobs,lastobs);
                   13554:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13555: #ifdef GSL
1.136     brouard  13556: #endif
1.186     brouard  13557:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13558:   /* Standard  */
                   13559:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13560:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13561:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13562:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13563:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13564:     for (k=1; k<=npar;k++)
                   13565:       printf(" %d %8.5f",k,p[k]);
                   13566:     printf("\n");
1.205     brouard  13567:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13568:       /* mlikeli uses func not funcone */
1.247     brouard  13569:       /* for(i=1;i<nlstate;i++){ */
                   13570:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13571:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13572:       /* } */
1.205     brouard  13573:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13574:     }
                   13575:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13576:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13577:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13578:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13579:     }
                   13580:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13581:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13582:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13583:           /* exit(0); */
1.126     brouard  13584:     for (k=1; k<=npar;k++)
                   13585:       printf(" %d %8.5f",k,p[k]);
                   13586:     printf("\n");
                   13587:     
                   13588:     /*--------- results files --------------*/
1.283     brouard  13589:     /* 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  13590:     
                   13591:     
                   13592:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13593:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13594:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13595: 
                   13596:     printf("#model=  1      +     age ");
                   13597:     fprintf(ficres,"#model=  1      +     age ");
                   13598:     fprintf(ficlog,"#model=  1      +     age ");
                   13599:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13600: </ul>", model);
                   13601: 
                   13602:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13603:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13604:     if(nagesqr==1){
                   13605:       printf("  + age*age  ");
                   13606:       fprintf(ficres,"  + age*age  ");
                   13607:       fprintf(ficlog,"  + age*age  ");
                   13608:       fprintf(fichtm, "<th>+ age*age</th>");
                   13609:     }
                   13610:     for(j=1;j <=ncovmodel-2;j++){
                   13611:       if(Typevar[j]==0) {
                   13612:        printf("  +      V%d  ",Tvar[j]);
                   13613:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13614:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13615:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13616:       }else if(Typevar[j]==1) {
                   13617:        printf("  +    V%d*age ",Tvar[j]);
                   13618:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13619:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13620:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13621:       }else if(Typevar[j]==2) {
                   13622:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13623:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13624:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13625:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13626:       }
                   13627:     }
                   13628:     printf("\n");
                   13629:     fprintf(ficres,"\n");
                   13630:     fprintf(ficlog,"\n");
                   13631:     fprintf(fichtm, "</tr>");
                   13632:     fprintf(fichtm, "\n");
                   13633:     
                   13634:     
1.126     brouard  13635:     for(i=1,jk=1; i <=nlstate; i++){
                   13636:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13637:        if (k != i) {
1.319     brouard  13638:          fprintf(fichtm, "<tr>");
1.225     brouard  13639:          printf("%d%d ",i,k);
                   13640:          fprintf(ficlog,"%d%d ",i,k);
                   13641:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13642:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13643:          for(j=1; j <=ncovmodel; j++){
                   13644:            printf("%12.7f ",p[jk]);
                   13645:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13646:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13647:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13648:            jk++; 
                   13649:          }
                   13650:          printf("\n");
                   13651:          fprintf(ficlog,"\n");
                   13652:          fprintf(ficres,"\n");
1.319     brouard  13653:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13654:        }
1.126     brouard  13655:       }
                   13656:     }
1.319     brouard  13657:     /* fprintf(fichtm,"</tr>\n"); */
                   13658:     fprintf(fichtm,"</table>\n");
                   13659:     fprintf(fichtm, "\n");
                   13660: 
1.203     brouard  13661:     if(mle != 0){
                   13662:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13663:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13664:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13665:       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");
                   13666:       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  13667:       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  13668:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13669:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13670:       if(nagesqr==1){
                   13671:        printf("  + age*age  ");
                   13672:        fprintf(ficres,"  + age*age  ");
                   13673:        fprintf(ficlog,"  + age*age  ");
                   13674:        fprintf(fichtm, "<th>+ age*age</th>");
                   13675:       }
                   13676:       for(j=1;j <=ncovmodel-2;j++){
                   13677:        if(Typevar[j]==0) {
                   13678:          printf("  +      V%d  ",Tvar[j]);
                   13679:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13680:        }else if(Typevar[j]==1) {
                   13681:          printf("  +    V%d*age ",Tvar[j]);
                   13682:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13683:        }else if(Typevar[j]==2) {
                   13684:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13685:        }
                   13686:       }
                   13687:       fprintf(fichtm, "</tr>\n");
                   13688:  
1.203     brouard  13689:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13690:        for(k=1; k <=(nlstate+ndeath); k++){
                   13691:          if (k != i) {
1.319     brouard  13692:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13693:            printf("%d%d ",i,k);
                   13694:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13695:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13696:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13697:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13698:              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]));
                   13699:              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  13700:              if(fabs(wald) > 1.96){
1.321     brouard  13701:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13702:              }else{
                   13703:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13704:              }
1.324     brouard  13705:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13706:              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  13707:              jk++; 
                   13708:            }
                   13709:            printf("\n");
                   13710:            fprintf(ficlog,"\n");
1.319     brouard  13711:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13712:          }
                   13713:        }
1.193     brouard  13714:       }
1.203     brouard  13715:     } /* end of hesscov and Wald tests */
1.319     brouard  13716:     fprintf(fichtm,"</table>\n");
1.225     brouard  13717:     
1.203     brouard  13718:     /*  */
1.126     brouard  13719:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13720:     printf("# Scales (for hessian or gradient estimation)\n");
                   13721:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13722:     for(i=1,jk=1; i <=nlstate; i++){
                   13723:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13724:        if (j!=i) {
                   13725:          fprintf(ficres,"%1d%1d",i,j);
                   13726:          printf("%1d%1d",i,j);
                   13727:          fprintf(ficlog,"%1d%1d",i,j);
                   13728:          for(k=1; k<=ncovmodel;k++){
                   13729:            printf(" %.5e",delti[jk]);
                   13730:            fprintf(ficlog," %.5e",delti[jk]);
                   13731:            fprintf(ficres," %.5e",delti[jk]);
                   13732:            jk++;
                   13733:          }
                   13734:          printf("\n");
                   13735:          fprintf(ficlog,"\n");
                   13736:          fprintf(ficres,"\n");
                   13737:        }
1.126     brouard  13738:       }
                   13739:     }
                   13740:     
                   13741:     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  13742:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13743:       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");
                   13744:     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");
                   13745:     /* # 121 Var(a12)\n\ */
                   13746:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13747:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13748:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13749:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13750:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13751:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13752:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13753:     
                   13754:     
                   13755:     /* Just to have a covariance matrix which will be more understandable
                   13756:        even is we still don't want to manage dictionary of variables
                   13757:     */
                   13758:     for(itimes=1;itimes<=2;itimes++){
                   13759:       jj=0;
                   13760:       for(i=1; i <=nlstate; i++){
1.225     brouard  13761:        for(j=1; j <=nlstate+ndeath; j++){
                   13762:          if(j==i) continue;
                   13763:          for(k=1; k<=ncovmodel;k++){
                   13764:            jj++;
                   13765:            ca[0]= k+'a'-1;ca[1]='\0';
                   13766:            if(itimes==1){
                   13767:              if(mle>=1)
                   13768:                printf("#%1d%1d%d",i,j,k);
                   13769:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13770:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13771:            }else{
                   13772:              if(mle>=1)
                   13773:                printf("%1d%1d%d",i,j,k);
                   13774:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13775:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13776:            }
                   13777:            ll=0;
                   13778:            for(li=1;li <=nlstate; li++){
                   13779:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13780:                if(lj==li) continue;
                   13781:                for(lk=1;lk<=ncovmodel;lk++){
                   13782:                  ll++;
                   13783:                  if(ll<=jj){
                   13784:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13785:                    if(ll<jj){
                   13786:                      if(itimes==1){
                   13787:                        if(mle>=1)
                   13788:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13789:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13790:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13791:                      }else{
                   13792:                        if(mle>=1)
                   13793:                          printf(" %.5e",matcov[jj][ll]); 
                   13794:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13795:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13796:                      }
                   13797:                    }else{
                   13798:                      if(itimes==1){
                   13799:                        if(mle>=1)
                   13800:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13801:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13802:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13803:                      }else{
                   13804:                        if(mle>=1)
                   13805:                          printf(" %.7e",matcov[jj][ll]); 
                   13806:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13807:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13808:                      }
                   13809:                    }
                   13810:                  }
                   13811:                } /* end lk */
                   13812:              } /* end lj */
                   13813:            } /* end li */
                   13814:            if(mle>=1)
                   13815:              printf("\n");
                   13816:            fprintf(ficlog,"\n");
                   13817:            fprintf(ficres,"\n");
                   13818:            numlinepar++;
                   13819:          } /* end k*/
                   13820:        } /*end j */
1.126     brouard  13821:       } /* end i */
                   13822:     } /* end itimes */
                   13823:     
                   13824:     fflush(ficlog);
                   13825:     fflush(ficres);
1.225     brouard  13826:     while(fgets(line, MAXLINE, ficpar)) {
                   13827:       /* If line starts with a # it is a comment */
                   13828:       if (line[0] == '#') {
                   13829:        numlinepar++;
                   13830:        fputs(line,stdout);
                   13831:        fputs(line,ficparo);
                   13832:        fputs(line,ficlog);
1.299     brouard  13833:        fputs(line,ficres);
1.225     brouard  13834:        continue;
                   13835:       }else
                   13836:        break;
                   13837:     }
                   13838:     
1.209     brouard  13839:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13840:     /*   ungetc(c,ficpar); */
                   13841:     /*   fgets(line, MAXLINE, ficpar); */
                   13842:     /*   fputs(line,stdout); */
                   13843:     /*   fputs(line,ficparo); */
                   13844:     /* } */
                   13845:     /* ungetc(c,ficpar); */
1.126     brouard  13846:     
                   13847:     estepm=0;
1.209     brouard  13848:     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  13849:       
                   13850:       if (num_filled != 6) {
                   13851:        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);
                   13852:        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);
                   13853:        goto end;
                   13854:       }
                   13855:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13856:     }
                   13857:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13858:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13859:     
1.209     brouard  13860:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13861:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13862:     if (fage <= 2) {
                   13863:       bage = ageminpar;
                   13864:       fage = agemaxpar;
                   13865:     }
                   13866:     
                   13867:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13868:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13869:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13870:                
1.186     brouard  13871:     /* Other stuffs, more or less useful */    
1.254     brouard  13872:     while(fgets(line, MAXLINE, ficpar)) {
                   13873:       /* If line starts with a # it is a comment */
                   13874:       if (line[0] == '#') {
                   13875:        numlinepar++;
                   13876:        fputs(line,stdout);
                   13877:        fputs(line,ficparo);
                   13878:        fputs(line,ficlog);
1.299     brouard  13879:        fputs(line,ficres);
1.254     brouard  13880:        continue;
                   13881:       }else
                   13882:        break;
                   13883:     }
                   13884: 
                   13885:     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){
                   13886:       
                   13887:       if (num_filled != 7) {
                   13888:        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);
                   13889:        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);
                   13890:        goto end;
                   13891:       }
                   13892:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13893:       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);
                   13894:       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);
                   13895:       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  13896:     }
1.254     brouard  13897: 
                   13898:     while(fgets(line, MAXLINE, ficpar)) {
                   13899:       /* If line starts with a # it is a comment */
                   13900:       if (line[0] == '#') {
                   13901:        numlinepar++;
                   13902:        fputs(line,stdout);
                   13903:        fputs(line,ficparo);
                   13904:        fputs(line,ficlog);
1.299     brouard  13905:        fputs(line,ficres);
1.254     brouard  13906:        continue;
                   13907:       }else
                   13908:        break;
1.126     brouard  13909:     }
                   13910:     
                   13911:     
                   13912:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13913:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13914:     
1.254     brouard  13915:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13916:       if (num_filled != 1) {
                   13917:        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);
                   13918:        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);
                   13919:        goto end;
                   13920:       }
                   13921:       printf("pop_based=%d\n",popbased);
                   13922:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13923:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13924:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13925:     }
                   13926:      
1.258     brouard  13927:     /* Results */
1.332     brouard  13928:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13929:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13930:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13931:     endishere=0;
1.258     brouard  13932:     nresult=0;
1.308     brouard  13933:     parameterline=0;
1.258     brouard  13934:     do{
                   13935:       if(!fgets(line, MAXLINE, ficpar)){
                   13936:        endishere=1;
1.308     brouard  13937:        parameterline=15;
1.258     brouard  13938:       }else if (line[0] == '#') {
                   13939:        /* If line starts with a # it is a comment */
1.254     brouard  13940:        numlinepar++;
                   13941:        fputs(line,stdout);
                   13942:        fputs(line,ficparo);
                   13943:        fputs(line,ficlog);
1.299     brouard  13944:        fputs(line,ficres);
1.254     brouard  13945:        continue;
1.258     brouard  13946:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13947:        parameterline=11;
1.296     brouard  13948:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13949:        parameterline=12;
1.307     brouard  13950:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13951:        parameterline=13;
1.307     brouard  13952:       }
1.258     brouard  13953:       else{
                   13954:        parameterline=14;
1.254     brouard  13955:       }
1.308     brouard  13956:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13957:       case 11:
1.296     brouard  13958:        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)){
                   13959:                  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  13960:          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);
                   13961:          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);
                   13962:          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);
                   13963:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13964:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13965:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13966:           prvforecast = 1;
                   13967:        } 
                   13968:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13969:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13970:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13971:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13972:           prvforecast = 2;
                   13973:        }
                   13974:        else {
                   13975:          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);
                   13976:          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);
                   13977:          goto end;
1.258     brouard  13978:        }
1.254     brouard  13979:        break;
1.258     brouard  13980:       case 12:
1.296     brouard  13981:        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)){
                   13982:           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);
                   13983:          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);
                   13984:          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);
                   13985:          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);
                   13986:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13987:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13988:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13989:           prvbackcast = 1;
                   13990:        } 
                   13991:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13992:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13993:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13994:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13995:           prvbackcast = 2;
                   13996:        }
                   13997:        else {
                   13998:          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);
                   13999:          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);
                   14000:          goto end;
1.258     brouard  14001:        }
1.230     brouard  14002:        break;
1.258     brouard  14003:       case 13:
1.332     brouard  14004:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14005:        nresult++; /* Sum of resultlines */
1.342     brouard  14006:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14007:        /* removefirstspace(&resultlineori); */
                   14008:        
                   14009:        if(strstr(resultlineori,"v") !=0){
                   14010:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14011:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14012:          return 1;
                   14013:        }
                   14014:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14015:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14016:        if(nresult > MAXRESULTLINESPONE-1){
                   14017:          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);
                   14018:          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  14019:          goto end;
                   14020:        }
1.332     brouard  14021:        
1.310     brouard  14022:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14023:          fprintf(ficparo,"result: %s\n",resultline);
                   14024:          fprintf(ficres,"result: %s\n",resultline);
                   14025:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14026:        } else
                   14027:          goto end;
1.307     brouard  14028:        break;
                   14029:       case 14:
                   14030:        printf("Error: Unknown command '%s'\n",line);
                   14031:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14032:        if(line[0] == ' ' || line[0] == '\n'){
                   14033:          printf("It should not be an empty line '%s'\n",line);
                   14034:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14035:        }         
1.307     brouard  14036:        if(ncovmodel >=2 && nresult==0 ){
                   14037:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14038:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14039:        }
1.307     brouard  14040:        /* goto end; */
                   14041:        break;
1.308     brouard  14042:       case 15:
                   14043:        printf("End of resultlines.\n");
                   14044:        fprintf(ficlog,"End of resultlines.\n");
                   14045:        break;
                   14046:       default: /* parameterline =0 */
1.307     brouard  14047:        nresult=1;
                   14048:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14049:       } /* End switch parameterline */
                   14050:     }while(endishere==0); /* End do */
1.126     brouard  14051:     
1.230     brouard  14052:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14053:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14054:     
                   14055:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14056:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14057:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14058: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14059: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14060:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14061: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14062: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14063:     }else{
1.270     brouard  14064:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14065:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14066:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14067:       if(prvforecast==1){
                   14068:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14069:         jprojd=jproj1;
                   14070:         mprojd=mproj1;
                   14071:         anprojd=anproj1;
                   14072:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14073:         jprojf=jproj2;
                   14074:         mprojf=mproj2;
                   14075:         anprojf=anproj2;
                   14076:       } else if(prvforecast == 2){
                   14077:         dateprojd=dateintmean;
                   14078:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14079:         dateprojf=dateintmean+yrfproj;
                   14080:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14081:       }
                   14082:       if(prvbackcast==1){
                   14083:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14084:         jbackd=jback1;
                   14085:         mbackd=mback1;
                   14086:         anbackd=anback1;
                   14087:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14088:         jbackf=jback2;
                   14089:         mbackf=mback2;
                   14090:         anbackf=anback2;
                   14091:       } else if(prvbackcast == 2){
                   14092:         datebackd=dateintmean;
                   14093:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14094:         datebackf=dateintmean-yrbproj;
                   14095:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14096:       }
                   14097:       
                   14098:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  14099:     }
                   14100:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14101:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14102:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14103:                
1.225     brouard  14104:     /*------------ free_vector  -------------*/
                   14105:     /*  chdir(path); */
1.220     brouard  14106:                
1.215     brouard  14107:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14108:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14109:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14110:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14111:     free_lvector(num,firstobs,lastobs);
                   14112:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14113:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14114:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14115:     fclose(ficparo);
                   14116:     fclose(ficres);
1.220     brouard  14117:                
                   14118:                
1.186     brouard  14119:     /* Other results (useful)*/
1.220     brouard  14120:                
                   14121:                
1.126     brouard  14122:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14123:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14124:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14125:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14126:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14127:     fclose(ficrespl);
                   14128: 
                   14129:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14130:     /*#include "hpijx.h"*/
1.332     brouard  14131:     /** 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?*/
                   14132:     /* calls hpxij with combination k */
1.180     brouard  14133:     hPijx(p, bage, fage);
1.145     brouard  14134:     fclose(ficrespij);
1.227     brouard  14135:     
1.220     brouard  14136:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14137:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14138:     k=1;
1.126     brouard  14139:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14140:     
1.269     brouard  14141:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14142:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14143:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14144:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14145:        for(k=1;k<=ncovcombmax;k++)
                   14146:          probs[i][j][k]=0.;
1.269     brouard  14147:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14148:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14149:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14150:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14151:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14152:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14153:          for(k=1;k<=ncovcombmax;k++)
                   14154:            mobaverages[i][j][k]=0.;
1.219     brouard  14155:       mobaverage=mobaverages;
                   14156:       if (mobilav!=0) {
1.235     brouard  14157:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14158:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14159:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14160:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14161:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14162:        }
1.269     brouard  14163:       } else if (mobilavproj !=0) {
1.235     brouard  14164:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14165:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14166:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14167:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14168:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14169:        }
1.269     brouard  14170:       }else{
                   14171:        printf("Internal error moving average\n");
                   14172:        fflush(stdout);
                   14173:        exit(1);
1.219     brouard  14174:       }
                   14175:     }/* end if moving average */
1.227     brouard  14176:     
1.126     brouard  14177:     /*---------- Forecasting ------------------*/
1.296     brouard  14178:     if(prevfcast==1){ 
                   14179:       /*   /\*    if(stepm ==1){*\/ */
                   14180:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14181:       /*This done previously after freqsummary.*/
                   14182:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14183:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14184:       
                   14185:       /* } else if (prvforecast==2){ */
                   14186:       /*   /\*    if(stepm ==1){*\/ */
                   14187:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14188:       /* } */
                   14189:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14190:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14191:     }
1.269     brouard  14192: 
1.296     brouard  14193:     /* Prevbcasting */
                   14194:     if(prevbcast==1){
1.219     brouard  14195:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14196:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14197:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14198: 
                   14199:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14200: 
                   14201:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14202: 
1.219     brouard  14203:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14204:       fclose(ficresplb);
                   14205: 
1.222     brouard  14206:       hBijx(p, bage, fage, mobaverage);
                   14207:       fclose(ficrespijb);
1.219     brouard  14208: 
1.296     brouard  14209:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14210:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14211:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14212:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14213:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14214:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14215: 
                   14216:       
1.269     brouard  14217:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14218: 
                   14219:       
1.269     brouard  14220:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14221:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14222:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14223:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14224:     }    /* end  Prevbcasting */
1.268     brouard  14225:  
1.186     brouard  14226:  
                   14227:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14228: 
1.215     brouard  14229:     free_ivector(wav,1,imx);
                   14230:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14231:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14232:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14233:                
                   14234:                
1.127     brouard  14235:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14236:                
1.201     brouard  14237:     strcpy(filerese,"E_");
                   14238:     strcat(filerese,fileresu);
1.126     brouard  14239:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14240:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14241:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14242:     }
1.208     brouard  14243:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14244:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14245: 
                   14246:     pstamp(ficreseij);
1.219     brouard  14247:                
1.235     brouard  14248:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14249:     if (cptcovn < 1){i1=1;}
                   14250:     
                   14251:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14252:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14253:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14254:        continue;
1.219     brouard  14255:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14256:       printf("\n#****** ");
1.225     brouard  14257:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14258:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14259:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14260:       }
                   14261:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14262:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14263:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14264:       }
                   14265:       fprintf(ficreseij,"******\n");
1.235     brouard  14266:       printf("******\n");
1.219     brouard  14267:       
                   14268:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14269:       oldm=oldms;savm=savms;
1.330     brouard  14270:       /* 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  14271:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14272:       
1.219     brouard  14273:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14274:     }
                   14275:     fclose(ficreseij);
1.208     brouard  14276:     printf("done evsij\n");fflush(stdout);
                   14277:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14278: 
1.218     brouard  14279:                
1.227     brouard  14280:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14281:     /* Should be moved in a function */                
1.201     brouard  14282:     strcpy(filerest,"T_");
                   14283:     strcat(filerest,fileresu);
1.127     brouard  14284:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14285:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14286:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14287:     }
1.208     brouard  14288:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14289:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14290:     strcpy(fileresstde,"STDE_");
                   14291:     strcat(fileresstde,fileresu);
1.126     brouard  14292:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14293:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14294:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14295:     }
1.227     brouard  14296:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14297:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14298: 
1.201     brouard  14299:     strcpy(filerescve,"CVE_");
                   14300:     strcat(filerescve,fileresu);
1.126     brouard  14301:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14302:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14303:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14304:     }
1.227     brouard  14305:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14306:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14307: 
1.201     brouard  14308:     strcpy(fileresv,"V_");
                   14309:     strcat(fileresv,fileresu);
1.126     brouard  14310:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14311:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14312:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14313:     }
1.227     brouard  14314:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14315:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14316: 
1.235     brouard  14317:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14318:     if (cptcovn < 1){i1=1;}
                   14319:     
1.334     brouard  14320:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14321:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14322:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14323:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14324:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14325:       /* */
                   14326:       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  14327:        continue;
1.321     brouard  14328:       printf("\n# model %s \n#****** Result for:", model);
                   14329:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14330:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14331:       /* It might not be a good idea to mix dummies and quantitative */
                   14332:       /* 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 *\/ */
                   14333:       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 */
                   14334:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14335:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14336:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14337:         * (V5 is quanti) V4 and V3 are dummies
                   14338:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14339:         *                                                              l=1 l=2
                   14340:         *                                                           k=1  1   1   0   0
                   14341:         *                                                           k=2  2   1   1   0
                   14342:         *                                                           k=3 [1] [2]  0   1
                   14343:         *                                                           k=4  2   2   1   1
                   14344:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14345:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14346:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14347:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14348:         */
                   14349:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14350:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14351: /* We give up with the combinations!! */
1.342     brouard  14352:        /* if(debugILK) */
                   14353:        /*   printf("\n j=%d In computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d Fixed[modelresult[nres][j]]=%d\n", j, nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff,Fixed[modelresult[nres][j]]);  /\* end if dummy  or quanti *\/ */
1.334     brouard  14354: 
                   14355:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.344   ! brouard  14356:          /* printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /\* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  *\/ */ /* TinvDoQresult[nres][Name of the variable] */
        !          14357:          printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordered by the covariate values in the resultline  */
        !          14358:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
        !          14359:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  14360:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14361:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14362:          }else{
                   14363:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14364:          }
                   14365:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14366:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14367:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14368:          /* For each selected (single) quantitative value */
1.337     brouard  14369:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14370:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14371:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14372:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14373:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14374:          }else{
                   14375:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14376:          }
                   14377:        }else{
                   14378:          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 */
                   14379:          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 */
                   14380:          exit(1);
                   14381:        }
1.335     brouard  14382:       } /* End loop for each variable in the resultline */
1.334     brouard  14383:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14384:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14385:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14386:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14387:       /* }      */
1.208     brouard  14388:       fprintf(ficrest,"******\n");
1.227     brouard  14389:       fprintf(ficlog,"******\n");
                   14390:       printf("******\n");
1.208     brouard  14391:       
                   14392:       fprintf(ficresstdeij,"\n#****** ");
                   14393:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14394:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14395:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14396:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14397:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14398:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14399:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14400:       }
                   14401:       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  14402:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14403:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14404:       }        
1.208     brouard  14405:       fprintf(ficresstdeij,"******\n");
                   14406:       fprintf(ficrescveij,"******\n");
                   14407:       
                   14408:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14409:       /* pstamp(ficresvij); */
1.225     brouard  14410:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14411:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14412:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14413:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14414:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14415:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14416:       }        
1.208     brouard  14417:       fprintf(ficresvij,"******\n");
                   14418:       
                   14419:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14420:       oldm=oldms;savm=savms;
1.235     brouard  14421:       printf(" cvevsij ");
                   14422:       fprintf(ficlog, " cvevsij ");
                   14423:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14424:       printf(" end cvevsij \n ");
                   14425:       fprintf(ficlog, " end cvevsij \n ");
                   14426:       
                   14427:       /*
                   14428:        */
                   14429:       /* goto endfree; */
                   14430:       
                   14431:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14432:       pstamp(ficrest);
                   14433:       
1.269     brouard  14434:       epj=vector(1,nlstate+1);
1.208     brouard  14435:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14436:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14437:        cptcod= 0; /* To be deleted */
                   14438:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14439:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14440:        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  14441:        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 ");
                   14442:        if(vpopbased==1)
                   14443:          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);
                   14444:        else
1.288     brouard  14445:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14446:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14447:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14448:        fprintf(ficrest,"\n");
                   14449:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14450:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14451:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14452:        for(age=bage; age <=fage ;age++){
1.235     brouard  14453:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14454:          if (vpopbased==1) {
                   14455:            if(mobilav ==0){
                   14456:              for(i=1; i<=nlstate;i++)
                   14457:                prlim[i][i]=probs[(int)age][i][k];
                   14458:            }else{ /* mobilav */ 
                   14459:              for(i=1; i<=nlstate;i++)
                   14460:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14461:            }
                   14462:          }
1.219     brouard  14463:          
1.227     brouard  14464:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14465:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14466:          /* printf(" age %4.0f ",age); */
                   14467:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14468:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14469:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14470:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14471:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14472:            }
                   14473:            epj[nlstate+1] +=epj[j];
                   14474:          }
                   14475:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14476:          
1.227     brouard  14477:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14478:            for(j=1;j <=nlstate;j++)
                   14479:              vepp += vareij[i][j][(int)age];
                   14480:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14481:          for(j=1;j <=nlstate;j++){
                   14482:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14483:          }
                   14484:          fprintf(ficrest,"\n");
                   14485:        }
1.208     brouard  14486:       } /* End vpopbased */
1.269     brouard  14487:       free_vector(epj,1,nlstate+1);
1.208     brouard  14488:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14489:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14490:       printf("done selection\n");fflush(stdout);
                   14491:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14492:       
1.335     brouard  14493:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14494: 
                   14495:     printf("done State-specific expectancies\n");fflush(stdout);
                   14496:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14497: 
1.335     brouard  14498:     /* variance-covariance of forward period prevalence */
1.269     brouard  14499:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14500: 
1.227     brouard  14501:     
1.290     brouard  14502:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14503:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14504:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14505:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14506:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14507:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14508:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14509:     free_ivector(tab,1,NCOVMAX);
                   14510:     fclose(ficresstdeij);
                   14511:     fclose(ficrescveij);
                   14512:     fclose(ficresvij);
                   14513:     fclose(ficrest);
                   14514:     fclose(ficpar);
                   14515:     
                   14516:     
1.126     brouard  14517:     /*---------- End : free ----------------*/
1.219     brouard  14518:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14519:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14520:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14521:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14522:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14523:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14524:   /* endfree:*/
                   14525:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14526:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14527:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  14528:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   14529:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14530:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14531:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14532:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14533:   free_matrix(matcov,1,npar,1,npar);
                   14534:   free_matrix(hess,1,npar,1,npar);
                   14535:   /*free_vector(delti,1,npar);*/
                   14536:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14537:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14538:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14539:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14540:   
                   14541:   free_ivector(ncodemax,1,NCOVMAX);
                   14542:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14543:   free_ivector(Dummy,-1,NCOVMAX);
                   14544:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14545:   free_ivector(DummyV,1,NCOVMAX);
                   14546:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14547:   free_ivector(Typevar,-1,NCOVMAX);
                   14548:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14549:   free_ivector(TvarsQ,1,NCOVMAX);
                   14550:   free_ivector(TvarsQind,1,NCOVMAX);
                   14551:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14552:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14553:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14554:   free_ivector(TvarFD,1,NCOVMAX);
                   14555:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14556:   free_ivector(TvarF,1,NCOVMAX);
                   14557:   free_ivector(TvarFind,1,NCOVMAX);
                   14558:   free_ivector(TvarV,1,NCOVMAX);
                   14559:   free_ivector(TvarVind,1,NCOVMAX);
                   14560:   free_ivector(TvarA,1,NCOVMAX);
                   14561:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14562:   free_ivector(TvarFQ,1,NCOVMAX);
                   14563:   free_ivector(TvarFQind,1,NCOVMAX);
                   14564:   free_ivector(TvarVD,1,NCOVMAX);
                   14565:   free_ivector(TvarVDind,1,NCOVMAX);
                   14566:   free_ivector(TvarVQ,1,NCOVMAX);
                   14567:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14568:   free_ivector(TvarVV,1,NCOVMAX);
                   14569:   free_ivector(TvarVVind,1,NCOVMAX);
                   14570:   
1.230     brouard  14571:   free_ivector(Tvarsel,1,NCOVMAX);
                   14572:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14573:   free_ivector(Tposprod,1,NCOVMAX);
                   14574:   free_ivector(Tprod,1,NCOVMAX);
                   14575:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14576:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14577:   free_ivector(Tage,1,NCOVMAX);
                   14578:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14579:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14580:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14581: 
                   14582:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14583: 
1.227     brouard  14584:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14585:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14586:   fflush(fichtm);
                   14587:   fflush(ficgp);
                   14588:   
1.227     brouard  14589:   
1.126     brouard  14590:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14591:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14592:     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  14593:   }else{
                   14594:     printf("End of Imach\n");
                   14595:     fprintf(ficlog,"End of Imach\n");
                   14596:   }
                   14597:   printf("See log file on %s\n",filelog);
                   14598:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14599:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14600:   rend_time = time(NULL);  
                   14601:   end_time = *localtime(&rend_time);
                   14602:   /* tml = *localtime(&end_time.tm_sec); */
                   14603:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14604:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14605:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14606:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14607:   
1.157     brouard  14608:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14609:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14610:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14611:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14612: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14613:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14614:   fclose(fichtm);
                   14615:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14616:   fclose(fichtmcov);
                   14617:   fclose(ficgp);
                   14618:   fclose(ficlog);
                   14619:   /*------ End -----------*/
1.227     brouard  14620:   
1.281     brouard  14621: 
                   14622: /* Executes gnuplot */
1.227     brouard  14623:   
                   14624:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14625: #ifdef WIN32
1.227     brouard  14626:   if (_chdir(pathcd) != 0)
                   14627:     printf("Can't move to directory %s!\n",path);
                   14628:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14629: #else
1.227     brouard  14630:     if(chdir(pathcd) != 0)
                   14631:       printf("Can't move to directory %s!\n", path);
                   14632:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14633: #endif 
1.126     brouard  14634:     printf("Current directory %s!\n",pathcd);
                   14635:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14636:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14637: #ifdef _WIN32
1.126     brouard  14638:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14639: #endif
                   14640:   if(!stat(plotcmd,&info)){
1.158     brouard  14641:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14642:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14643:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14644:     }else
                   14645:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14646: #ifdef __unix
1.126     brouard  14647:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14648:     if(!stat(plotcmd,&info)){
1.158     brouard  14649:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14650:     }else
                   14651:       strcpy(pplotcmd,plotcmd);
                   14652: #endif
                   14653:   }else
                   14654:     strcpy(pplotcmd,plotcmd);
                   14655:   
                   14656:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14657:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14658:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14659:   
1.126     brouard  14660:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14661:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14662:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14663:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14664:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14665:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14666:       strcpy(plotcmd,pplotcmd);
                   14667:     }
1.126     brouard  14668:   }
1.158     brouard  14669:   printf(" Successful, please wait...");
1.126     brouard  14670:   while (z[0] != 'q') {
                   14671:     /* chdir(path); */
1.154     brouard  14672:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14673:     scanf("%s",z);
                   14674: /*     if (z[0] == 'c') system("./imach"); */
                   14675:     if (z[0] == 'e') {
1.158     brouard  14676: #ifdef __APPLE__
1.152     brouard  14677:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14678: #elif __linux
                   14679:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14680: #else
1.152     brouard  14681:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14682: #endif
                   14683:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14684:       system(pplotcmd);
1.126     brouard  14685:     }
                   14686:     else if (z[0] == 'g') system(plotcmd);
                   14687:     else if (z[0] == 'q') exit(0);
                   14688:   }
1.227     brouard  14689: end:
1.126     brouard  14690:   while (z[0] != 'q') {
1.195     brouard  14691:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14692:     scanf("%s",z);
                   14693:   }
1.283     brouard  14694:   printf("End\n");
1.282     brouard  14695:   exit(0);
1.126     brouard  14696: }

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