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

1.333   ! brouard     1: /* $Id: imach.c,v 1.332 2022/08/21 09:06:25 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.333   ! brouard     4:   Revision 1.332  2022/08/21 09:06:25  brouard
        !             5:   Summary: Version 0.99r33
        !             6: 
        !             7:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
        !             8:   reassigning covariates: my first idea was that people will always
        !             9:   use the first covariate V1 into the model but in fact they are
        !            10:   producing data with many covariates and can use an equation model
        !            11:   with some of the covariate; it means that in a model V2+V3 instead
        !            12:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
        !            13:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
        !            14:   the equation model is restricted to two variables only (V2, V3)
        !            15:   and the combination for V2 should be codtabm(k,1) instead of
        !            16:   (codtabm(k,2), and the code should be
        !            17:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
        !            18:   made. All of these should be simplified once a day like we did in
        !            19:   hpxij() for example by using precov[nres] which is computed in
        !            20:   decoderesult for each nres of each resultline. Loop should be done
        !            21:   on the equation model globally by distinguishing only product with
        !            22:   age (which are changing with age) and no more on type of
        !            23:   covariates, single dummies, single covariates.
        !            24: 
1.332     brouard    25:   Revision 1.331  2022/08/07 05:40:09  brouard
                     26:   *** empty log message ***
                     27: 
1.331     brouard    28:   Revision 1.330  2022/08/06 07:18:25  brouard
                     29:   Summary: last 0.99r31
                     30: 
                     31:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     32: 
1.330     brouard    33:   Revision 1.329  2022/08/03 17:29:54  brouard
                     34:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     35: 
1.329     brouard    36:   Revision 1.328  2022/07/27 17:40:48  brouard
                     37:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     38: 
1.328     brouard    39:   Revision 1.327  2022/07/27 14:47:35  brouard
                     40:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     41: 
1.327     brouard    42:   Revision 1.326  2022/07/26 17:33:55  brouard
                     43:   Summary: some test with nres=1
                     44: 
1.326     brouard    45:   Revision 1.325  2022/07/25 14:27:23  brouard
                     46:   Summary: r30
                     47: 
                     48:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     49:   coredumped, revealed by Feiuno, thank you.
                     50: 
1.325     brouard    51:   Revision 1.324  2022/07/23 17:44:26  brouard
                     52:   *** empty log message ***
                     53: 
1.324     brouard    54:   Revision 1.323  2022/07/22 12:30:08  brouard
                     55:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     56: 
1.323     brouard    57:   Revision 1.322  2022/07/22 12:27:48  brouard
                     58:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     59: 
1.322     brouard    60:   Revision 1.321  2022/07/22 12:04:24  brouard
                     61:   Summary: r28
                     62: 
                     63:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     64: 
1.321     brouard    65:   Revision 1.320  2022/06/02 05:10:11  brouard
                     66:   *** empty log message ***
                     67: 
1.320     brouard    68:   Revision 1.319  2022/06/02 04:45:11  brouard
                     69:   * imach.c (Module): Adding the Wald tests from the log to the main
                     70:   htm for better display of the maximum likelihood estimators.
                     71: 
1.319     brouard    72:   Revision 1.318  2022/05/24 08:10:59  brouard
                     73:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     74:   of confidencce intervals with product in the equation modelC
                     75: 
1.318     brouard    76:   Revision 1.317  2022/05/15 15:06:23  brouard
                     77:   * imach.c (Module):  Some minor improvements
                     78: 
1.317     brouard    79:   Revision 1.316  2022/05/11 15:11:31  brouard
                     80:   Summary: r27
                     81: 
1.316     brouard    82:   Revision 1.315  2022/05/11 15:06:32  brouard
                     83:   *** empty log message ***
                     84: 
1.315     brouard    85:   Revision 1.314  2022/04/13 17:43:09  brouard
                     86:   * imach.c (Module): Adding link to text data files
                     87: 
1.314     brouard    88:   Revision 1.313  2022/04/11 15:57:42  brouard
                     89:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     90: 
1.313     brouard    91:   Revision 1.312  2022/04/05 21:24:39  brouard
                     92:   *** empty log message ***
                     93: 
1.312     brouard    94:   Revision 1.311  2022/04/05 21:03:51  brouard
                     95:   Summary: Fixed quantitative covariates
                     96: 
                     97:          Fixed covariates (dummy or quantitative)
                     98:        with missing values have never been allowed but are ERRORS and
                     99:        program quits. Standard deviations of fixed covariates were
                    100:        wrongly computed. Mean and standard deviations of time varying
                    101:        covariates are still not computed.
                    102: 
1.311     brouard   103:   Revision 1.310  2022/03/17 08:45:53  brouard
                    104:   Summary: 99r25
                    105: 
                    106:   Improving detection of errors: result lines should be compatible with
                    107:   the model.
                    108: 
1.310     brouard   109:   Revision 1.309  2021/05/20 12:39:14  brouard
                    110:   Summary: Version 0.99r24
                    111: 
1.309     brouard   112:   Revision 1.308  2021/03/31 13:11:57  brouard
                    113:   Summary: Version 0.99r23
                    114: 
                    115: 
                    116:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    117: 
1.308     brouard   118:   Revision 1.307  2021/03/08 18:11:32  brouard
                    119:   Summary: 0.99r22 fixed bug on result:
                    120: 
1.307     brouard   121:   Revision 1.306  2021/02/20 15:44:02  brouard
                    122:   Summary: Version 0.99r21
                    123: 
                    124:   * imach.c (Module): Fix bug on quitting after result lines!
                    125:   (Module): Version 0.99r21
                    126: 
1.306     brouard   127:   Revision 1.305  2021/02/20 15:28:30  brouard
                    128:   * imach.c (Module): Fix bug on quitting after result lines!
                    129: 
1.305     brouard   130:   Revision 1.304  2021/02/12 11:34:20  brouard
                    131:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    132: 
1.304     brouard   133:   Revision 1.303  2021/02/11 19:50:15  brouard
                    134:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    135: 
1.303     brouard   136:   Revision 1.302  2020/02/22 21:00:05  brouard
                    137:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    138:   and life table from the data without any state)
                    139: 
1.302     brouard   140:   Revision 1.301  2019/06/04 13:51:20  brouard
                    141:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    142: 
1.301     brouard   143:   Revision 1.300  2019/05/22 19:09:45  brouard
                    144:   Summary: version 0.99r19 of May 2019
                    145: 
1.300     brouard   146:   Revision 1.299  2019/05/22 18:37:08  brouard
                    147:   Summary: Cleaned 0.99r19
                    148: 
1.299     brouard   149:   Revision 1.298  2019/05/22 18:19:56  brouard
                    150:   *** empty log message ***
                    151: 
1.298     brouard   152:   Revision 1.297  2019/05/22 17:56:10  brouard
                    153:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    154: 
1.297     brouard   155:   Revision 1.296  2019/05/20 13:03:18  brouard
                    156:   Summary: Projection syntax simplified
                    157: 
                    158: 
                    159:   We can now start projections, forward or backward, from the mean date
                    160:   of inteviews up to or down to a number of years of projection:
                    161:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    162:   or
                    163:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    164:   or
                    165:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    166:   or
                    167:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    168: 
1.296     brouard   169:   Revision 1.295  2019/05/18 09:52:50  brouard
                    170:   Summary: doxygen tex bug
                    171: 
1.295     brouard   172:   Revision 1.294  2019/05/16 14:54:33  brouard
                    173:   Summary: There was some wrong lines added
                    174: 
1.294     brouard   175:   Revision 1.293  2019/05/09 15:17:34  brouard
                    176:   *** empty log message ***
                    177: 
1.293     brouard   178:   Revision 1.292  2019/05/09 14:17:20  brouard
                    179:   Summary: Some updates
                    180: 
1.292     brouard   181:   Revision 1.291  2019/05/09 13:44:18  brouard
                    182:   Summary: Before ncovmax
                    183: 
1.291     brouard   184:   Revision 1.290  2019/05/09 13:39:37  brouard
                    185:   Summary: 0.99r18 unlimited number of individuals
                    186: 
                    187:   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.
                    188: 
1.290     brouard   189:   Revision 1.289  2018/12/13 09:16:26  brouard
                    190:   Summary: Bug for young ages (<-30) will be in r17
                    191: 
1.289     brouard   192:   Revision 1.288  2018/05/02 20:58:27  brouard
                    193:   Summary: Some bugs fixed
                    194: 
1.288     brouard   195:   Revision 1.287  2018/05/01 17:57:25  brouard
                    196:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    197: 
1.287     brouard   198:   Revision 1.286  2018/04/27 14:27:04  brouard
                    199:   Summary: some minor bugs
                    200: 
1.286     brouard   201:   Revision 1.285  2018/04/21 21:02:16  brouard
                    202:   Summary: Some bugs fixed, valgrind tested
                    203: 
1.285     brouard   204:   Revision 1.284  2018/04/20 05:22:13  brouard
                    205:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    206: 
1.284     brouard   207:   Revision 1.283  2018/04/19 14:49:16  brouard
                    208:   Summary: Some minor bugs fixed
                    209: 
1.283     brouard   210:   Revision 1.282  2018/02/27 22:50:02  brouard
                    211:   *** empty log message ***
                    212: 
1.282     brouard   213:   Revision 1.281  2018/02/27 19:25:23  brouard
                    214:   Summary: Adding second argument for quitting
                    215: 
1.281     brouard   216:   Revision 1.280  2018/02/21 07:58:13  brouard
                    217:   Summary: 0.99r15
                    218: 
                    219:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    220: 
1.280     brouard   221:   Revision 1.279  2017/07/20 13:35:01  brouard
                    222:   Summary: temporary working
                    223: 
1.279     brouard   224:   Revision 1.278  2017/07/19 14:09:02  brouard
                    225:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    226: 
1.278     brouard   227:   Revision 1.277  2017/07/17 08:53:49  brouard
                    228:   Summary: BOM files can be read now
                    229: 
1.277     brouard   230:   Revision 1.276  2017/06/30 15:48:31  brouard
                    231:   Summary: Graphs improvements
                    232: 
1.276     brouard   233:   Revision 1.275  2017/06/30 13:39:33  brouard
                    234:   Summary: Saito's color
                    235: 
1.275     brouard   236:   Revision 1.274  2017/06/29 09:47:08  brouard
                    237:   Summary: Version 0.99r14
                    238: 
1.274     brouard   239:   Revision 1.273  2017/06/27 11:06:02  brouard
                    240:   Summary: More documentation on projections
                    241: 
1.273     brouard   242:   Revision 1.272  2017/06/27 10:22:40  brouard
                    243:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    244: 
1.272     brouard   245:   Revision 1.271  2017/06/27 10:17:50  brouard
                    246:   Summary: Some bug with rint
                    247: 
1.271     brouard   248:   Revision 1.270  2017/05/24 05:45:29  brouard
                    249:   *** empty log message ***
                    250: 
1.270     brouard   251:   Revision 1.269  2017/05/23 08:39:25  brouard
                    252:   Summary: Code into subroutine, cleanings
                    253: 
1.269     brouard   254:   Revision 1.268  2017/05/18 20:09:32  brouard
                    255:   Summary: backprojection and confidence intervals of backprevalence
                    256: 
1.268     brouard   257:   Revision 1.267  2017/05/13 10:25:05  brouard
                    258:   Summary: temporary save for backprojection
                    259: 
1.267     brouard   260:   Revision 1.266  2017/05/13 07:26:12  brouard
                    261:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    262: 
1.266     brouard   263:   Revision 1.265  2017/04/26 16:22:11  brouard
                    264:   Summary: imach 0.99r13 Some bugs fixed
                    265: 
1.265     brouard   266:   Revision 1.264  2017/04/26 06:01:29  brouard
                    267:   Summary: Labels in graphs
                    268: 
1.264     brouard   269:   Revision 1.263  2017/04/24 15:23:15  brouard
                    270:   Summary: to save
                    271: 
1.263     brouard   272:   Revision 1.262  2017/04/18 16:48:12  brouard
                    273:   *** empty log message ***
                    274: 
1.262     brouard   275:   Revision 1.261  2017/04/05 10:14:09  brouard
                    276:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    277: 
1.261     brouard   278:   Revision 1.260  2017/04/04 17:46:59  brouard
                    279:   Summary: Gnuplot indexations fixed (humm)
                    280: 
1.260     brouard   281:   Revision 1.259  2017/04/04 13:01:16  brouard
                    282:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    283: 
1.259     brouard   284:   Revision 1.258  2017/04/03 10:17:47  brouard
                    285:   Summary: Version 0.99r12
                    286: 
                    287:   Some cleanings, conformed with updated documentation.
                    288: 
1.258     brouard   289:   Revision 1.257  2017/03/29 16:53:30  brouard
                    290:   Summary: Temp
                    291: 
1.257     brouard   292:   Revision 1.256  2017/03/27 05:50:23  brouard
                    293:   Summary: Temporary
                    294: 
1.256     brouard   295:   Revision 1.255  2017/03/08 16:02:28  brouard
                    296:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    297: 
1.255     brouard   298:   Revision 1.254  2017/03/08 07:13:00  brouard
                    299:   Summary: Fixing data parameter line
                    300: 
1.254     brouard   301:   Revision 1.253  2016/12/15 11:59:41  brouard
                    302:   Summary: 0.99 in progress
                    303: 
1.253     brouard   304:   Revision 1.252  2016/09/15 21:15:37  brouard
                    305:   *** empty log message ***
                    306: 
1.252     brouard   307:   Revision 1.251  2016/09/15 15:01:13  brouard
                    308:   Summary: not working
                    309: 
1.251     brouard   310:   Revision 1.250  2016/09/08 16:07:27  brouard
                    311:   Summary: continue
                    312: 
1.250     brouard   313:   Revision 1.249  2016/09/07 17:14:18  brouard
                    314:   Summary: Starting values from frequencies
                    315: 
1.249     brouard   316:   Revision 1.248  2016/09/07 14:10:18  brouard
                    317:   *** empty log message ***
                    318: 
1.248     brouard   319:   Revision 1.247  2016/09/02 11:11:21  brouard
                    320:   *** empty log message ***
                    321: 
1.247     brouard   322:   Revision 1.246  2016/09/02 08:49:22  brouard
                    323:   *** empty log message ***
                    324: 
1.246     brouard   325:   Revision 1.245  2016/09/02 07:25:01  brouard
                    326:   *** empty log message ***
                    327: 
1.245     brouard   328:   Revision 1.244  2016/09/02 07:17:34  brouard
                    329:   *** empty log message ***
                    330: 
1.244     brouard   331:   Revision 1.243  2016/09/02 06:45:35  brouard
                    332:   *** empty log message ***
                    333: 
1.243     brouard   334:   Revision 1.242  2016/08/30 15:01:20  brouard
                    335:   Summary: Fixing a lots
                    336: 
1.242     brouard   337:   Revision 1.241  2016/08/29 17:17:25  brouard
                    338:   Summary: gnuplot problem in Back projection to fix
                    339: 
1.241     brouard   340:   Revision 1.240  2016/08/29 07:53:18  brouard
                    341:   Summary: Better
                    342: 
1.240     brouard   343:   Revision 1.239  2016/08/26 15:51:03  brouard
                    344:   Summary: Improvement in Powell output in order to copy and paste
                    345: 
                    346:   Author:
                    347: 
1.239     brouard   348:   Revision 1.238  2016/08/26 14:23:35  brouard
                    349:   Summary: Starting tests of 0.99
                    350: 
1.238     brouard   351:   Revision 1.237  2016/08/26 09:20:19  brouard
                    352:   Summary: to valgrind
                    353: 
1.237     brouard   354:   Revision 1.236  2016/08/25 10:50:18  brouard
                    355:   *** empty log message ***
                    356: 
1.236     brouard   357:   Revision 1.235  2016/08/25 06:59:23  brouard
                    358:   *** empty log message ***
                    359: 
1.235     brouard   360:   Revision 1.234  2016/08/23 16:51:20  brouard
                    361:   *** empty log message ***
                    362: 
1.234     brouard   363:   Revision 1.233  2016/08/23 07:40:50  brouard
                    364:   Summary: not working
                    365: 
1.233     brouard   366:   Revision 1.232  2016/08/22 14:20:21  brouard
                    367:   Summary: not working
                    368: 
1.232     brouard   369:   Revision 1.231  2016/08/22 07:17:15  brouard
                    370:   Summary: not working
                    371: 
1.231     brouard   372:   Revision 1.230  2016/08/22 06:55:53  brouard
                    373:   Summary: Not working
                    374: 
1.230     brouard   375:   Revision 1.229  2016/07/23 09:45:53  brouard
                    376:   Summary: Completing for func too
                    377: 
1.229     brouard   378:   Revision 1.228  2016/07/22 17:45:30  brouard
                    379:   Summary: Fixing some arrays, still debugging
                    380: 
1.227     brouard   381:   Revision 1.226  2016/07/12 18:42:34  brouard
                    382:   Summary: temp
                    383: 
1.226     brouard   384:   Revision 1.225  2016/07/12 08:40:03  brouard
                    385:   Summary: saving but not running
                    386: 
1.225     brouard   387:   Revision 1.224  2016/07/01 13:16:01  brouard
                    388:   Summary: Fixes
                    389: 
1.224     brouard   390:   Revision 1.223  2016/02/19 09:23:35  brouard
                    391:   Summary: temporary
                    392: 
1.223     brouard   393:   Revision 1.222  2016/02/17 08:14:50  brouard
                    394:   Summary: Probably last 0.98 stable version 0.98r6
                    395: 
1.222     brouard   396:   Revision 1.221  2016/02/15 23:35:36  brouard
                    397:   Summary: minor bug
                    398: 
1.220     brouard   399:   Revision 1.219  2016/02/15 00:48:12  brouard
                    400:   *** empty log message ***
                    401: 
1.219     brouard   402:   Revision 1.218  2016/02/12 11:29:23  brouard
                    403:   Summary: 0.99 Back projections
                    404: 
1.218     brouard   405:   Revision 1.217  2015/12/23 17:18:31  brouard
                    406:   Summary: Experimental backcast
                    407: 
1.217     brouard   408:   Revision 1.216  2015/12/18 17:32:11  brouard
                    409:   Summary: 0.98r4 Warning and status=-2
                    410: 
                    411:   Version 0.98r4 is now:
                    412:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    413:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    414:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    415: 
1.216     brouard   416:   Revision 1.215  2015/12/16 08:52:24  brouard
                    417:   Summary: 0.98r4 working
                    418: 
1.215     brouard   419:   Revision 1.214  2015/12/16 06:57:54  brouard
                    420:   Summary: temporary not working
                    421: 
1.214     brouard   422:   Revision 1.213  2015/12/11 18:22:17  brouard
                    423:   Summary: 0.98r4
                    424: 
1.213     brouard   425:   Revision 1.212  2015/11/21 12:47:24  brouard
                    426:   Summary: minor typo
                    427: 
1.212     brouard   428:   Revision 1.211  2015/11/21 12:41:11  brouard
                    429:   Summary: 0.98r3 with some graph of projected cross-sectional
                    430: 
                    431:   Author: Nicolas Brouard
                    432: 
1.211     brouard   433:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   434:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   435:   Summary: Adding ftolpl parameter
                    436:   Author: N Brouard
                    437: 
                    438:   We had difficulties to get smoothed confidence intervals. It was due
                    439:   to the period prevalence which wasn't computed accurately. The inner
                    440:   parameter ftolpl is now an outer parameter of the .imach parameter
                    441:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    442:   computation are long.
                    443: 
1.209     brouard   444:   Revision 1.208  2015/11/17 14:31:57  brouard
                    445:   Summary: temporary
                    446: 
1.208     brouard   447:   Revision 1.207  2015/10/27 17:36:57  brouard
                    448:   *** empty log message ***
                    449: 
1.207     brouard   450:   Revision 1.206  2015/10/24 07:14:11  brouard
                    451:   *** empty log message ***
                    452: 
1.206     brouard   453:   Revision 1.205  2015/10/23 15:50:53  brouard
                    454:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    455: 
1.205     brouard   456:   Revision 1.204  2015/10/01 16:20:26  brouard
                    457:   Summary: Some new graphs of contribution to likelihood
                    458: 
1.204     brouard   459:   Revision 1.203  2015/09/30 17:45:14  brouard
                    460:   Summary: looking at better estimation of the hessian
                    461: 
                    462:   Also a better criteria for convergence to the period prevalence And
                    463:   therefore adding the number of years needed to converge. (The
                    464:   prevalence in any alive state shold sum to one
                    465: 
1.203     brouard   466:   Revision 1.202  2015/09/22 19:45:16  brouard
                    467:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    468: 
1.202     brouard   469:   Revision 1.201  2015/09/15 17:34:58  brouard
                    470:   Summary: 0.98r0
                    471: 
                    472:   - Some new graphs like suvival functions
                    473:   - Some bugs fixed like model=1+age+V2.
                    474: 
1.201     brouard   475:   Revision 1.200  2015/09/09 16:53:55  brouard
                    476:   Summary: Big bug thanks to Flavia
                    477: 
                    478:   Even model=1+age+V2. did not work anymore
                    479: 
1.200     brouard   480:   Revision 1.199  2015/09/07 14:09:23  brouard
                    481:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    482: 
1.199     brouard   483:   Revision 1.198  2015/09/03 07:14:39  brouard
                    484:   Summary: 0.98q5 Flavia
                    485: 
1.198     brouard   486:   Revision 1.197  2015/09/01 18:24:39  brouard
                    487:   *** empty log message ***
                    488: 
1.197     brouard   489:   Revision 1.196  2015/08/18 23:17:52  brouard
                    490:   Summary: 0.98q5
                    491: 
1.196     brouard   492:   Revision 1.195  2015/08/18 16:28:39  brouard
                    493:   Summary: Adding a hack for testing purpose
                    494: 
                    495:   After reading the title, ftol and model lines, if the comment line has
                    496:   a q, starting with #q, the answer at the end of the run is quit. It
                    497:   permits to run test files in batch with ctest. The former workaround was
                    498:   $ echo q | imach foo.imach
                    499: 
1.195     brouard   500:   Revision 1.194  2015/08/18 13:32:00  brouard
                    501:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    502: 
1.194     brouard   503:   Revision 1.193  2015/08/04 07:17:42  brouard
                    504:   Summary: 0.98q4
                    505: 
1.193     brouard   506:   Revision 1.192  2015/07/16 16:49:02  brouard
                    507:   Summary: Fixing some outputs
                    508: 
1.192     brouard   509:   Revision 1.191  2015/07/14 10:00:33  brouard
                    510:   Summary: Some fixes
                    511: 
1.191     brouard   512:   Revision 1.190  2015/05/05 08:51:13  brouard
                    513:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    514: 
                    515:   Fix 1+age+.
                    516: 
1.190     brouard   517:   Revision 1.189  2015/04/30 14:45:16  brouard
                    518:   Summary: 0.98q2
                    519: 
1.189     brouard   520:   Revision 1.188  2015/04/30 08:27:53  brouard
                    521:   *** empty log message ***
                    522: 
1.188     brouard   523:   Revision 1.187  2015/04/29 09:11:15  brouard
                    524:   *** empty log message ***
                    525: 
1.187     brouard   526:   Revision 1.186  2015/04/23 12:01:52  brouard
                    527:   Summary: V1*age is working now, version 0.98q1
                    528: 
                    529:   Some codes had been disabled in order to simplify and Vn*age was
                    530:   working in the optimization phase, ie, giving correct MLE parameters,
                    531:   but, as usual, outputs were not correct and program core dumped.
                    532: 
1.186     brouard   533:   Revision 1.185  2015/03/11 13:26:42  brouard
                    534:   Summary: Inclusion of compile and links command line for Intel Compiler
                    535: 
1.185     brouard   536:   Revision 1.184  2015/03/11 11:52:39  brouard
                    537:   Summary: Back from Windows 8. Intel Compiler
                    538: 
1.184     brouard   539:   Revision 1.183  2015/03/10 20:34:32  brouard
                    540:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    541: 
                    542:   We use directest instead of original Powell test; probably no
                    543:   incidence on the results, but better justifications;
                    544:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    545:   wrong results.
                    546: 
1.183     brouard   547:   Revision 1.182  2015/02/12 08:19:57  brouard
                    548:   Summary: Trying to keep directest which seems simpler and more general
                    549:   Author: Nicolas Brouard
                    550: 
1.182     brouard   551:   Revision 1.181  2015/02/11 23:22:24  brouard
                    552:   Summary: Comments on Powell added
                    553: 
                    554:   Author:
                    555: 
1.181     brouard   556:   Revision 1.180  2015/02/11 17:33:45  brouard
                    557:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    558: 
1.180     brouard   559:   Revision 1.179  2015/01/04 09:57:06  brouard
                    560:   Summary: back to OS/X
                    561: 
1.179     brouard   562:   Revision 1.178  2015/01/04 09:35:48  brouard
                    563:   *** empty log message ***
                    564: 
1.178     brouard   565:   Revision 1.177  2015/01/03 18:40:56  brouard
                    566:   Summary: Still testing ilc32 on OSX
                    567: 
1.177     brouard   568:   Revision 1.176  2015/01/03 16:45:04  brouard
                    569:   *** empty log message ***
                    570: 
1.176     brouard   571:   Revision 1.175  2015/01/03 16:33:42  brouard
                    572:   *** empty log message ***
                    573: 
1.175     brouard   574:   Revision 1.174  2015/01/03 16:15:49  brouard
                    575:   Summary: Still in cross-compilation
                    576: 
1.174     brouard   577:   Revision 1.173  2015/01/03 12:06:26  brouard
                    578:   Summary: trying to detect cross-compilation
                    579: 
1.173     brouard   580:   Revision 1.172  2014/12/27 12:07:47  brouard
                    581:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    582: 
1.172     brouard   583:   Revision 1.171  2014/12/23 13:26:59  brouard
                    584:   Summary: Back from Visual C
                    585: 
                    586:   Still problem with utsname.h on Windows
                    587: 
1.171     brouard   588:   Revision 1.170  2014/12/23 11:17:12  brouard
                    589:   Summary: Cleaning some \%% back to %%
                    590: 
                    591:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    592: 
1.170     brouard   593:   Revision 1.169  2014/12/22 23:08:31  brouard
                    594:   Summary: 0.98p
                    595: 
                    596:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    597: 
1.169     brouard   598:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   599:   Summary: update
1.169     brouard   600: 
1.168     brouard   601:   Revision 1.167  2014/12/22 13:50:56  brouard
                    602:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    603: 
                    604:   Testing on Linux 64
                    605: 
1.167     brouard   606:   Revision 1.166  2014/12/22 11:40:47  brouard
                    607:   *** empty log message ***
                    608: 
1.166     brouard   609:   Revision 1.165  2014/12/16 11:20:36  brouard
                    610:   Summary: After compiling on Visual C
                    611: 
                    612:   * imach.c (Module): Merging 1.61 to 1.162
                    613: 
1.165     brouard   614:   Revision 1.164  2014/12/16 10:52:11  brouard
                    615:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    616: 
                    617:   * imach.c (Module): Merging 1.61 to 1.162
                    618: 
1.164     brouard   619:   Revision 1.163  2014/12/16 10:30:11  brouard
                    620:   * imach.c (Module): Merging 1.61 to 1.162
                    621: 
1.163     brouard   622:   Revision 1.162  2014/09/25 11:43:39  brouard
                    623:   Summary: temporary backup 0.99!
                    624: 
1.162     brouard   625:   Revision 1.1  2014/09/16 11:06:58  brouard
                    626:   Summary: With some code (wrong) for nlopt
                    627: 
                    628:   Author:
                    629: 
                    630:   Revision 1.161  2014/09/15 20:41:41  brouard
                    631:   Summary: Problem with macro SQR on Intel compiler
                    632: 
1.161     brouard   633:   Revision 1.160  2014/09/02 09:24:05  brouard
                    634:   *** empty log message ***
                    635: 
1.160     brouard   636:   Revision 1.159  2014/09/01 10:34:10  brouard
                    637:   Summary: WIN32
                    638:   Author: Brouard
                    639: 
1.159     brouard   640:   Revision 1.158  2014/08/27 17:11:51  brouard
                    641:   *** empty log message ***
                    642: 
1.158     brouard   643:   Revision 1.157  2014/08/27 16:26:55  brouard
                    644:   Summary: Preparing windows Visual studio version
                    645:   Author: Brouard
                    646: 
                    647:   In order to compile on Visual studio, time.h is now correct and time_t
                    648:   and tm struct should be used. difftime should be used but sometimes I
                    649:   just make the differences in raw time format (time(&now).
                    650:   Trying to suppress #ifdef LINUX
                    651:   Add xdg-open for __linux in order to open default browser.
                    652: 
1.157     brouard   653:   Revision 1.156  2014/08/25 20:10:10  brouard
                    654:   *** empty log message ***
                    655: 
1.156     brouard   656:   Revision 1.155  2014/08/25 18:32:34  brouard
                    657:   Summary: New compile, minor changes
                    658:   Author: Brouard
                    659: 
1.155     brouard   660:   Revision 1.154  2014/06/20 17:32:08  brouard
                    661:   Summary: Outputs now all graphs of convergence to period prevalence
                    662: 
1.154     brouard   663:   Revision 1.153  2014/06/20 16:45:46  brouard
                    664:   Summary: If 3 live state, convergence to period prevalence on same graph
                    665:   Author: Brouard
                    666: 
1.153     brouard   667:   Revision 1.152  2014/06/18 17:54:09  brouard
                    668:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    669: 
1.152     brouard   670:   Revision 1.151  2014/06/18 16:43:30  brouard
                    671:   *** empty log message ***
                    672: 
1.151     brouard   673:   Revision 1.150  2014/06/18 16:42:35  brouard
                    674:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    675:   Author: brouard
                    676: 
1.150     brouard   677:   Revision 1.149  2014/06/18 15:51:14  brouard
                    678:   Summary: Some fixes in parameter files errors
                    679:   Author: Nicolas Brouard
                    680: 
1.149     brouard   681:   Revision 1.148  2014/06/17 17:38:48  brouard
                    682:   Summary: Nothing new
                    683:   Author: Brouard
                    684: 
                    685:   Just a new packaging for OS/X version 0.98nS
                    686: 
1.148     brouard   687:   Revision 1.147  2014/06/16 10:33:11  brouard
                    688:   *** empty log message ***
                    689: 
1.147     brouard   690:   Revision 1.146  2014/06/16 10:20:28  brouard
                    691:   Summary: Merge
                    692:   Author: Brouard
                    693: 
                    694:   Merge, before building revised version.
                    695: 
1.146     brouard   696:   Revision 1.145  2014/06/10 21:23:15  brouard
                    697:   Summary: Debugging with valgrind
                    698:   Author: Nicolas Brouard
                    699: 
                    700:   Lot of changes in order to output the results with some covariates
                    701:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    702:   improve the code.
                    703:   No more memory valgrind error but a lot has to be done in order to
                    704:   continue the work of splitting the code into subroutines.
                    705:   Also, decodemodel has been improved. Tricode is still not
                    706:   optimal. nbcode should be improved. Documentation has been added in
                    707:   the source code.
                    708: 
1.144     brouard   709:   Revision 1.143  2014/01/26 09:45:38  brouard
                    710:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    711: 
                    712:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    713:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    714: 
1.143     brouard   715:   Revision 1.142  2014/01/26 03:57:36  brouard
                    716:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    717: 
                    718:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    719: 
1.142     brouard   720:   Revision 1.141  2014/01/26 02:42:01  brouard
                    721:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    722: 
1.141     brouard   723:   Revision 1.140  2011/09/02 10:37:54  brouard
                    724:   Summary: times.h is ok with mingw32 now.
                    725: 
1.140     brouard   726:   Revision 1.139  2010/06/14 07:50:17  brouard
                    727:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    728:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    729: 
1.139     brouard   730:   Revision 1.138  2010/04/30 18:19:40  brouard
                    731:   *** empty log message ***
                    732: 
1.138     brouard   733:   Revision 1.137  2010/04/29 18:11:38  brouard
                    734:   (Module): Checking covariates for more complex models
                    735:   than V1+V2. A lot of change to be done. Unstable.
                    736: 
1.137     brouard   737:   Revision 1.136  2010/04/26 20:30:53  brouard
                    738:   (Module): merging some libgsl code. Fixing computation
                    739:   of likelione (using inter/intrapolation if mle = 0) in order to
                    740:   get same likelihood as if mle=1.
                    741:   Some cleaning of code and comments added.
                    742: 
1.136     brouard   743:   Revision 1.135  2009/10/29 15:33:14  brouard
                    744:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    745: 
1.135     brouard   746:   Revision 1.134  2009/10/29 13:18:53  brouard
                    747:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    748: 
1.134     brouard   749:   Revision 1.133  2009/07/06 10:21:25  brouard
                    750:   just nforces
                    751: 
1.133     brouard   752:   Revision 1.132  2009/07/06 08:22:05  brouard
                    753:   Many tings
                    754: 
1.132     brouard   755:   Revision 1.131  2009/06/20 16:22:47  brouard
                    756:   Some dimensions resccaled
                    757: 
1.131     brouard   758:   Revision 1.130  2009/05/26 06:44:34  brouard
                    759:   (Module): Max Covariate is now set to 20 instead of 8. A
                    760:   lot of cleaning with variables initialized to 0. Trying to make
                    761:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    762: 
1.130     brouard   763:   Revision 1.129  2007/08/31 13:49:27  lievre
                    764:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    765: 
1.129     lievre    766:   Revision 1.128  2006/06/30 13:02:05  brouard
                    767:   (Module): Clarifications on computing e.j
                    768: 
1.128     brouard   769:   Revision 1.127  2006/04/28 18:11:50  brouard
                    770:   (Module): Yes the sum of survivors was wrong since
                    771:   imach-114 because nhstepm was no more computed in the age
                    772:   loop. Now we define nhstepma in the age loop.
                    773:   (Module): In order to speed up (in case of numerous covariates) we
                    774:   compute health expectancies (without variances) in a first step
                    775:   and then all the health expectancies with variances or standard
                    776:   deviation (needs data from the Hessian matrices) which slows the
                    777:   computation.
                    778:   In the future we should be able to stop the program is only health
                    779:   expectancies and graph are needed without standard deviations.
                    780: 
1.127     brouard   781:   Revision 1.126  2006/04/28 17:23:28  brouard
                    782:   (Module): Yes the sum of survivors was wrong since
                    783:   imach-114 because nhstepm was no more computed in the age
                    784:   loop. Now we define nhstepma in the age loop.
                    785:   Version 0.98h
                    786: 
1.126     brouard   787:   Revision 1.125  2006/04/04 15:20:31  lievre
                    788:   Errors in calculation of health expectancies. Age was not initialized.
                    789:   Forecasting file added.
                    790: 
                    791:   Revision 1.124  2006/03/22 17:13:53  lievre
                    792:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    793:   The log-likelihood is printed in the log file
                    794: 
                    795:   Revision 1.123  2006/03/20 10:52:43  brouard
                    796:   * imach.c (Module): <title> changed, corresponds to .htm file
                    797:   name. <head> headers where missing.
                    798: 
                    799:   * imach.c (Module): Weights can have a decimal point as for
                    800:   English (a comma might work with a correct LC_NUMERIC environment,
                    801:   otherwise the weight is truncated).
                    802:   Modification of warning when the covariates values are not 0 or
                    803:   1.
                    804:   Version 0.98g
                    805: 
                    806:   Revision 1.122  2006/03/20 09:45:41  brouard
                    807:   (Module): Weights can have a decimal point as for
                    808:   English (a comma might work with a correct LC_NUMERIC environment,
                    809:   otherwise the weight is truncated).
                    810:   Modification of warning when the covariates values are not 0 or
                    811:   1.
                    812:   Version 0.98g
                    813: 
                    814:   Revision 1.121  2006/03/16 17:45:01  lievre
                    815:   * imach.c (Module): Comments concerning covariates added
                    816: 
                    817:   * imach.c (Module): refinements in the computation of lli if
                    818:   status=-2 in order to have more reliable computation if stepm is
                    819:   not 1 month. Version 0.98f
                    820: 
                    821:   Revision 1.120  2006/03/16 15:10:38  lievre
                    822:   (Module): refinements in the computation of lli if
                    823:   status=-2 in order to have more reliable computation if stepm is
                    824:   not 1 month. Version 0.98f
                    825: 
                    826:   Revision 1.119  2006/03/15 17:42:26  brouard
                    827:   (Module): Bug if status = -2, the loglikelihood was
                    828:   computed as likelihood omitting the logarithm. Version O.98e
                    829: 
                    830:   Revision 1.118  2006/03/14 18:20:07  brouard
                    831:   (Module): varevsij Comments added explaining the second
                    832:   table of variances if popbased=1 .
                    833:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    834:   (Module): Function pstamp added
                    835:   (Module): Version 0.98d
                    836: 
                    837:   Revision 1.117  2006/03/14 17:16:22  brouard
                    838:   (Module): varevsij Comments added explaining the second
                    839:   table of variances if popbased=1 .
                    840:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    841:   (Module): Function pstamp added
                    842:   (Module): Version 0.98d
                    843: 
                    844:   Revision 1.116  2006/03/06 10:29:27  brouard
                    845:   (Module): Variance-covariance wrong links and
                    846:   varian-covariance of ej. is needed (Saito).
                    847: 
                    848:   Revision 1.115  2006/02/27 12:17:45  brouard
                    849:   (Module): One freematrix added in mlikeli! 0.98c
                    850: 
                    851:   Revision 1.114  2006/02/26 12:57:58  brouard
                    852:   (Module): Some improvements in processing parameter
                    853:   filename with strsep.
                    854: 
                    855:   Revision 1.113  2006/02/24 14:20:24  brouard
                    856:   (Module): Memory leaks checks with valgrind and:
                    857:   datafile was not closed, some imatrix were not freed and on matrix
                    858:   allocation too.
                    859: 
                    860:   Revision 1.112  2006/01/30 09:55:26  brouard
                    861:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    862: 
                    863:   Revision 1.111  2006/01/25 20:38:18  brouard
                    864:   (Module): Lots of cleaning and bugs added (Gompertz)
                    865:   (Module): Comments can be added in data file. Missing date values
                    866:   can be a simple dot '.'.
                    867: 
                    868:   Revision 1.110  2006/01/25 00:51:50  brouard
                    869:   (Module): Lots of cleaning and bugs added (Gompertz)
                    870: 
                    871:   Revision 1.109  2006/01/24 19:37:15  brouard
                    872:   (Module): Comments (lines starting with a #) are allowed in data.
                    873: 
                    874:   Revision 1.108  2006/01/19 18:05:42  lievre
                    875:   Gnuplot problem appeared...
                    876:   To be fixed
                    877: 
                    878:   Revision 1.107  2006/01/19 16:20:37  brouard
                    879:   Test existence of gnuplot in imach path
                    880: 
                    881:   Revision 1.106  2006/01/19 13:24:36  brouard
                    882:   Some cleaning and links added in html output
                    883: 
                    884:   Revision 1.105  2006/01/05 20:23:19  lievre
                    885:   *** empty log message ***
                    886: 
                    887:   Revision 1.104  2005/09/30 16:11:43  lievre
                    888:   (Module): sump fixed, loop imx fixed, and simplifications.
                    889:   (Module): If the status is missing at the last wave but we know
                    890:   that the person is alive, then we can code his/her status as -2
                    891:   (instead of missing=-1 in earlier versions) and his/her
                    892:   contributions to the likelihood is 1 - Prob of dying from last
                    893:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    894:   the healthy state at last known wave). Version is 0.98
                    895: 
                    896:   Revision 1.103  2005/09/30 15:54:49  lievre
                    897:   (Module): sump fixed, loop imx fixed, and simplifications.
                    898: 
                    899:   Revision 1.102  2004/09/15 17:31:30  brouard
                    900:   Add the possibility to read data file including tab characters.
                    901: 
                    902:   Revision 1.101  2004/09/15 10:38:38  brouard
                    903:   Fix on curr_time
                    904: 
                    905:   Revision 1.100  2004/07/12 18:29:06  brouard
                    906:   Add version for Mac OS X. Just define UNIX in Makefile
                    907: 
                    908:   Revision 1.99  2004/06/05 08:57:40  brouard
                    909:   *** empty log message ***
                    910: 
                    911:   Revision 1.98  2004/05/16 15:05:56  brouard
                    912:   New version 0.97 . First attempt to estimate force of mortality
                    913:   directly from the data i.e. without the need of knowing the health
                    914:   state at each age, but using a Gompertz model: log u =a + b*age .
                    915:   This is the basic analysis of mortality and should be done before any
                    916:   other analysis, in order to test if the mortality estimated from the
                    917:   cross-longitudinal survey is different from the mortality estimated
                    918:   from other sources like vital statistic data.
                    919: 
                    920:   The same imach parameter file can be used but the option for mle should be -3.
                    921: 
1.324     brouard   922:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   923:   former routines in order to include the new code within the former code.
                    924: 
                    925:   The output is very simple: only an estimate of the intercept and of
                    926:   the slope with 95% confident intervals.
                    927: 
                    928:   Current limitations:
                    929:   A) Even if you enter covariates, i.e. with the
                    930:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    931:   B) There is no computation of Life Expectancy nor Life Table.
                    932: 
                    933:   Revision 1.97  2004/02/20 13:25:42  lievre
                    934:   Version 0.96d. Population forecasting command line is (temporarily)
                    935:   suppressed.
                    936: 
                    937:   Revision 1.96  2003/07/15 15:38:55  brouard
                    938:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    939:   rewritten within the same printf. Workaround: many printfs.
                    940: 
                    941:   Revision 1.95  2003/07/08 07:54:34  brouard
                    942:   * imach.c (Repository):
                    943:   (Repository): Using imachwizard code to output a more meaningful covariance
                    944:   matrix (cov(a12,c31) instead of numbers.
                    945: 
                    946:   Revision 1.94  2003/06/27 13:00:02  brouard
                    947:   Just cleaning
                    948: 
                    949:   Revision 1.93  2003/06/25 16:33:55  brouard
                    950:   (Module): On windows (cygwin) function asctime_r doesn't
                    951:   exist so I changed back to asctime which exists.
                    952:   (Module): Version 0.96b
                    953: 
                    954:   Revision 1.92  2003/06/25 16:30:45  brouard
                    955:   (Module): On windows (cygwin) function asctime_r doesn't
                    956:   exist so I changed back to asctime which exists.
                    957: 
                    958:   Revision 1.91  2003/06/25 15:30:29  brouard
                    959:   * imach.c (Repository): Duplicated warning errors corrected.
                    960:   (Repository): Elapsed time after each iteration is now output. It
                    961:   helps to forecast when convergence will be reached. Elapsed time
                    962:   is stamped in powell.  We created a new html file for the graphs
                    963:   concerning matrix of covariance. It has extension -cov.htm.
                    964: 
                    965:   Revision 1.90  2003/06/24 12:34:15  brouard
                    966:   (Module): Some bugs corrected for windows. Also, when
                    967:   mle=-1 a template is output in file "or"mypar.txt with the design
                    968:   of the covariance matrix to be input.
                    969: 
                    970:   Revision 1.89  2003/06/24 12:30:52  brouard
                    971:   (Module): Some bugs corrected for windows. Also, when
                    972:   mle=-1 a template is output in file "or"mypar.txt with the design
                    973:   of the covariance matrix to be input.
                    974: 
                    975:   Revision 1.88  2003/06/23 17:54:56  brouard
                    976:   * 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.
                    977: 
                    978:   Revision 1.87  2003/06/18 12:26:01  brouard
                    979:   Version 0.96
                    980: 
                    981:   Revision 1.86  2003/06/17 20:04:08  brouard
                    982:   (Module): Change position of html and gnuplot routines and added
                    983:   routine fileappend.
                    984: 
                    985:   Revision 1.85  2003/06/17 13:12:43  brouard
                    986:   * imach.c (Repository): Check when date of death was earlier that
                    987:   current date of interview. It may happen when the death was just
                    988:   prior to the death. In this case, dh was negative and likelihood
                    989:   was wrong (infinity). We still send an "Error" but patch by
                    990:   assuming that the date of death was just one stepm after the
                    991:   interview.
                    992:   (Repository): Because some people have very long ID (first column)
                    993:   we changed int to long in num[] and we added a new lvector for
                    994:   memory allocation. But we also truncated to 8 characters (left
                    995:   truncation)
                    996:   (Repository): No more line truncation errors.
                    997: 
                    998:   Revision 1.84  2003/06/13 21:44:43  brouard
                    999:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1000:   place. It differs from routine "prevalence" which may be called
                   1001:   many times. Probs is memory consuming and must be used with
                   1002:   parcimony.
                   1003:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1004: 
                   1005:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1006:   *** empty log message ***
                   1007: 
                   1008:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1009:   Add log in  imach.c and  fullversion number is now printed.
                   1010: 
                   1011: */
                   1012: /*
                   1013:    Interpolated Markov Chain
                   1014: 
                   1015:   Short summary of the programme:
                   1016:   
1.227     brouard  1017:   This program computes Healthy Life Expectancies or State-specific
                   1018:   (if states aren't health statuses) Expectancies from
                   1019:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1020: 
                   1021:   -1- a first survey ("cross") where individuals from different ages
                   1022:   are interviewed on their health status or degree of disability (in
                   1023:   the case of a health survey which is our main interest)
                   1024: 
                   1025:   -2- at least a second wave of interviews ("longitudinal") which
                   1026:   measure each change (if any) in individual health status.  Health
                   1027:   expectancies are computed from the time spent in each health state
                   1028:   according to a model. More health states you consider, more time is
                   1029:   necessary to reach the Maximum Likelihood of the parameters involved
                   1030:   in the model.  The simplest model is the multinomial logistic model
                   1031:   where pij is the probability to be observed in state j at the second
                   1032:   wave conditional to be observed in state i at the first
                   1033:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1034:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1035:   have a more complex model than "constant and age", you should modify
                   1036:   the program where the markup *Covariates have to be included here
                   1037:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1038:   convergence.
                   1039: 
                   1040:   The advantage of this computer programme, compared to a simple
                   1041:   multinomial logistic model, is clear when the delay between waves is not
                   1042:   identical for each individual. Also, if a individual missed an
                   1043:   intermediate interview, the information is lost, but taken into
                   1044:   account using an interpolation or extrapolation.  
                   1045: 
                   1046:   hPijx is the probability to be observed in state i at age x+h
                   1047:   conditional to the observed state i at age x. The delay 'h' can be
                   1048:   split into an exact number (nh*stepm) of unobserved intermediate
                   1049:   states. This elementary transition (by month, quarter,
                   1050:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1051:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1052:   and the contribution of each individual to the likelihood is simply
                   1053:   hPijx.
                   1054: 
                   1055:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1056:   of the life expectancies. It also computes the period (stable) prevalence.
                   1057: 
                   1058: Back prevalence and projections:
1.227     brouard  1059: 
                   1060:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1061:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1062:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1063:    mobilavproj)
                   1064: 
                   1065:     Computes the back prevalence limit for any combination of
                   1066:     covariate values k at any age between ageminpar and agemaxpar and
                   1067:     returns it in **bprlim. In the loops,
                   1068: 
                   1069:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1070:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1071: 
                   1072:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1073:    Computes for any combination of covariates k and any age between bage and fage 
                   1074:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1075:                        oldm=oldms;savm=savms;
1.227     brouard  1076: 
1.267     brouard  1077:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1078:      Computes the transition matrix starting at age 'age' over
                   1079:      'nhstepm*hstepm*stepm' months (i.e. until
                   1080:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1081:      nhstepm*hstepm matrices. 
                   1082: 
                   1083:      Returns p3mat[i][j][h] after calling
                   1084:      p3mat[i][j][h]=matprod2(newm,
                   1085:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1086:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1087:      oldm);
1.226     brouard  1088: 
                   1089: Important routines
                   1090: 
                   1091: - func (or funcone), computes logit (pij) distinguishing
                   1092:   o fixed variables (single or product dummies or quantitative);
                   1093:   o varying variables by:
                   1094:    (1) wave (single, product dummies, quantitative), 
                   1095:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1096:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1097:        % varying dummy (not done) or quantitative (not done);
                   1098: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1099:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1100: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1101:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1102:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1103: 
1.226     brouard  1104: 
                   1105:   
1.324     brouard  1106:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1107:            Institut national d'études démographiques, Paris.
1.126     brouard  1108:   This software have been partly granted by Euro-REVES, a concerted action
                   1109:   from the European Union.
                   1110:   It is copyrighted identically to a GNU software product, ie programme and
                   1111:   software can be distributed freely for non commercial use. Latest version
                   1112:   can be accessed at http://euroreves.ined.fr/imach .
                   1113: 
                   1114:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1115:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1116:   
                   1117:   **********************************************************************/
                   1118: /*
                   1119:   main
                   1120:   read parameterfile
                   1121:   read datafile
                   1122:   concatwav
                   1123:   freqsummary
                   1124:   if (mle >= 1)
                   1125:     mlikeli
                   1126:   print results files
                   1127:   if mle==1 
                   1128:      computes hessian
                   1129:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1130:       begin-prev-date,...
                   1131:   open gnuplot file
                   1132:   open html file
1.145     brouard  1133:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1134:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1135:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1136:     freexexit2 possible for memory heap.
                   1137: 
                   1138:   h Pij x                         | pij_nom  ficrestpij
                   1139:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1140:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1141:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1142: 
                   1143:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1144:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1145:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1146:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1147:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1148: 
1.126     brouard  1149:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1150:   health expectancies
                   1151:   Variance-covariance of DFLE
                   1152:   prevalence()
                   1153:    movingaverage()
                   1154:   varevsij() 
                   1155:   if popbased==1 varevsij(,popbased)
                   1156:   total life expectancies
                   1157:   Variance of period (stable) prevalence
                   1158:  end
                   1159: */
                   1160: 
1.187     brouard  1161: /* #define DEBUG */
                   1162: /* #define DEBUGBRENT */
1.203     brouard  1163: /* #define DEBUGLINMIN */
                   1164: /* #define DEBUGHESS */
                   1165: #define DEBUGHESSIJ
1.224     brouard  1166: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1167: #define POWELL /* Instead of NLOPT */
1.224     brouard  1168: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1169: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1170: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1171: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1172: 
                   1173: #include <math.h>
                   1174: #include <stdio.h>
                   1175: #include <stdlib.h>
                   1176: #include <string.h>
1.226     brouard  1177: #include <ctype.h>
1.159     brouard  1178: 
                   1179: #ifdef _WIN32
                   1180: #include <io.h>
1.172     brouard  1181: #include <windows.h>
                   1182: #include <tchar.h>
1.159     brouard  1183: #else
1.126     brouard  1184: #include <unistd.h>
1.159     brouard  1185: #endif
1.126     brouard  1186: 
                   1187: #include <limits.h>
                   1188: #include <sys/types.h>
1.171     brouard  1189: 
                   1190: #if defined(__GNUC__)
                   1191: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1192: #endif
                   1193: 
1.126     brouard  1194: #include <sys/stat.h>
                   1195: #include <errno.h>
1.159     brouard  1196: /* extern int errno; */
1.126     brouard  1197: 
1.157     brouard  1198: /* #ifdef LINUX */
                   1199: /* #include <time.h> */
                   1200: /* #include "timeval.h" */
                   1201: /* #else */
                   1202: /* #include <sys/time.h> */
                   1203: /* #endif */
                   1204: 
1.126     brouard  1205: #include <time.h>
                   1206: 
1.136     brouard  1207: #ifdef GSL
                   1208: #include <gsl/gsl_errno.h>
                   1209: #include <gsl/gsl_multimin.h>
                   1210: #endif
                   1211: 
1.167     brouard  1212: 
1.162     brouard  1213: #ifdef NLOPT
                   1214: #include <nlopt.h>
                   1215: typedef struct {
                   1216:   double (* function)(double [] );
                   1217: } myfunc_data ;
                   1218: #endif
                   1219: 
1.126     brouard  1220: /* #include <libintl.h> */
                   1221: /* #define _(String) gettext (String) */
                   1222: 
1.251     brouard  1223: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1224: 
                   1225: #define GNUPLOTPROGRAM "gnuplot"
                   1226: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1227: #define FILENAMELENGTH 256
1.126     brouard  1228: 
                   1229: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1230: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1231: 
1.144     brouard  1232: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1233: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1234: 
                   1235: #define NINTERVMAX 8
1.144     brouard  1236: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1237: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1238: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1239: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1240: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1241: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1242: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1243: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1244: /* #define AGESUP 130 */
1.288     brouard  1245: /* #define AGESUP 150 */
                   1246: #define AGESUP 200
1.268     brouard  1247: #define AGEINF 0
1.218     brouard  1248: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1249: #define AGEBASE 40
1.194     brouard  1250: #define AGEOVERFLOW 1.e20
1.164     brouard  1251: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1252: #ifdef _WIN32
                   1253: #define DIRSEPARATOR '\\'
                   1254: #define CHARSEPARATOR "\\"
                   1255: #define ODIRSEPARATOR '/'
                   1256: #else
1.126     brouard  1257: #define DIRSEPARATOR '/'
                   1258: #define CHARSEPARATOR "/"
                   1259: #define ODIRSEPARATOR '\\'
                   1260: #endif
                   1261: 
1.333   ! brouard  1262: /* $Id: imach.c,v 1.332 2022/08/21 09:06:25 brouard Exp $ */
1.126     brouard  1263: /* $State: Exp $ */
1.196     brouard  1264: #include "version.h"
                   1265: char version[]=__IMACH_VERSION__;
1.332     brouard  1266: char copyright[]="August 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.333   ! brouard  1267: char fullversion[]="$Revision: 1.332 $ $Date: 2022/08/21 09:06:25 $"; 
1.126     brouard  1268: char strstart[80];
                   1269: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1270: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1271: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1272: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1273: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   1274: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age */
                   1275: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   1276: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
1.225     brouard  1277: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1278: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1279: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.330     brouard  1280: int cptcoveff=0; /* Total number of covariates to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1281: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1282: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1283: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1284: int nsd=0; /**< Total number of single dummy variables (output) */
                   1285: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1286: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1287: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1288: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1289: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1290: int cptcov=0; /* Working variable */
1.290     brouard  1291: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1292: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1293: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1294: int nlstate=2; /* Number of live states */
                   1295: int ndeath=1; /* Number of dead states */
1.130     brouard  1296: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1297: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1298: int popbased=0;
                   1299: 
                   1300: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1301: int maxwav=0; /* Maxim number of waves */
                   1302: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1303: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1304: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1305:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1306: int mle=1, weightopt=0;
1.126     brouard  1307: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1308: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1309: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1310:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1311: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1312: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1313: 
1.130     brouard  1314: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1315: double **matprod2(); /* test */
1.126     brouard  1316: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1317: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1318: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1319: 
1.136     brouard  1320: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1321: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1322: FILE *ficlog, *ficrespow;
1.130     brouard  1323: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1324: double fretone; /* Only one call to likelihood */
1.130     brouard  1325: long ipmx=0; /* Number of contributions */
1.126     brouard  1326: double sw; /* Sum of weights */
                   1327: char filerespow[FILENAMELENGTH];
                   1328: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1329: FILE *ficresilk;
                   1330: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1331: FILE *ficresprobmorprev;
                   1332: FILE *fichtm, *fichtmcov; /* Html File */
                   1333: FILE *ficreseij;
                   1334: char filerese[FILENAMELENGTH];
                   1335: FILE *ficresstdeij;
                   1336: char fileresstde[FILENAMELENGTH];
                   1337: FILE *ficrescveij;
                   1338: char filerescve[FILENAMELENGTH];
                   1339: FILE  *ficresvij;
                   1340: char fileresv[FILENAMELENGTH];
1.269     brouard  1341: 
1.126     brouard  1342: char title[MAXLINE];
1.234     brouard  1343: char model[MAXLINE]; /**< The model line */
1.217     brouard  1344: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1345: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1346: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1347: char command[FILENAMELENGTH];
                   1348: int  outcmd=0;
                   1349: 
1.217     brouard  1350: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1351: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1352: char filelog[FILENAMELENGTH]; /* Log file */
                   1353: char filerest[FILENAMELENGTH];
                   1354: char fileregp[FILENAMELENGTH];
                   1355: char popfile[FILENAMELENGTH];
                   1356: 
                   1357: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1358: 
1.157     brouard  1359: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1360: /* struct timezone tzp; */
                   1361: /* extern int gettimeofday(); */
                   1362: struct tm tml, *gmtime(), *localtime();
                   1363: 
                   1364: extern time_t time();
                   1365: 
                   1366: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1367: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1368: struct tm tm;
                   1369: 
1.126     brouard  1370: char strcurr[80], strfor[80];
                   1371: 
                   1372: char *endptr;
                   1373: long lval;
                   1374: double dval;
                   1375: 
                   1376: #define NR_END 1
                   1377: #define FREE_ARG char*
                   1378: #define FTOL 1.0e-10
                   1379: 
                   1380: #define NRANSI 
1.240     brouard  1381: #define ITMAX 200
                   1382: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1383: 
                   1384: #define TOL 2.0e-4 
                   1385: 
                   1386: #define CGOLD 0.3819660 
                   1387: #define ZEPS 1.0e-10 
                   1388: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1389: 
                   1390: #define GOLD 1.618034 
                   1391: #define GLIMIT 100.0 
                   1392: #define TINY 1.0e-20 
                   1393: 
                   1394: static double maxarg1,maxarg2;
                   1395: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1396: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1397:   
                   1398: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1399: #define rint(a) floor(a+0.5)
1.166     brouard  1400: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1401: #define mytinydouble 1.0e-16
1.166     brouard  1402: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1403: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1404: /* static double dsqrarg; */
                   1405: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1406: static double sqrarg;
                   1407: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1408: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1409: int agegomp= AGEGOMP;
                   1410: 
                   1411: int imx; 
                   1412: int stepm=1;
                   1413: /* Stepm, step in month: minimum step interpolation*/
                   1414: 
                   1415: int estepm;
                   1416: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1417: 
                   1418: int m,nb;
                   1419: long *num;
1.197     brouard  1420: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1421: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1422:                   covariate for which somebody answered excluding 
                   1423:                   undefined. Usually 2: 0 and 1. */
                   1424: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1425:                             covariate for which somebody answered including 
                   1426:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1427: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1428: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1429: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1430: 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  1431: double *ageexmed,*agecens;
                   1432: double dateintmean=0;
1.296     brouard  1433:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1434:   double anprojf, mprojf, jprojf;
1.126     brouard  1435: 
1.296     brouard  1436:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1437:   double anbackf, mbackf, jbackf;
                   1438:   double jintmean,mintmean,aintmean;  
1.126     brouard  1439: double *weight;
                   1440: int **s; /* Status */
1.141     brouard  1441: double *agedc;
1.145     brouard  1442: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1443:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1444:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1445: double **coqvar; /* Fixed quantitative covariate nqv */
                   1446: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1447: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1448: double  idx; 
                   1449: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1450: /* Some documentation */
                   1451:       /*   Design original data
                   1452:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1453:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1454:        *                                                             ntv=3     nqtv=1
1.330     brouard  1455:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1456:        * For time varying covariate, quanti or dummies
                   1457:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1458:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1459:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1460:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1461:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1462:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1463:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1464:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1465:        */
                   1466: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1467: /* 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
                   1468:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1469:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1470: */
1.319     brouard  1471: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1472: /*    k        1  2   3   4     5    6    7     8    9 */
                   1473: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1474:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1475:                                                          /* product */
                   1476: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1477:                                                          /*(single or product without age), 2 dummy*/
                   1478:                                                          /* with age product, 3 quant with age product*/
                   1479: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1480: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1481: /*TnsdVar[Tvar]   1   2                              3 */ 
1.319     brouard  1482: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1483: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1484: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1485: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1486: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1487: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1488: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1489: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1490: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1491: /* 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  1492: /* 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  1493: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1494: /* Type                    */
                   1495: /* V         1  2  3  4  5 */
                   1496: /*           F  F  V  V  V */
                   1497: /*           D  Q  D  D  Q */
                   1498: /*                         */
                   1499: int *TvarsD;
1.330     brouard  1500: int *TnsdVar;
1.234     brouard  1501: int *TvarsDind;
                   1502: int *TvarsQ;
                   1503: int *TvarsQind;
                   1504: 
1.318     brouard  1505: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1506: int nresult=0;
1.258     brouard  1507: int parameterline=0; /* # of the parameter (type) line */
1.318     brouard  1508: int TKresult[MAXRESULTLINESPONE];
1.330     brouard  1509: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
1.318     brouard  1510: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
1.332     brouard  1511: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1512: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.318     brouard  1513: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For dummy variable , variable # (output) */
1.332     brouard  1514: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1515: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1516: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1517: 
                   1518: /* 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
                   1519:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1520:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1521: */
1.234     brouard  1522: /* 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  1523: 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 */
                   1524: 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 */
                   1525: 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 */
                   1526: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1527: 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 */
                   1528: 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  1529: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1530: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1531: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1532: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1533: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1534: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1535: 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 */
                   1536: 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 */
                   1537: 
1.230     brouard  1538: int *Tvarsel; /**< Selected covariates for output */
                   1539: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1540: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1541: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1542: 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  1543: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1544: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1545: int *Tage;
1.227     brouard  1546: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1547: 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  1548: 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*/ 
                   1549: 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  1550: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1551: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1552: int **Tvard;
1.330     brouard  1553: int **Tvardk;
1.227     brouard  1554: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1555: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1556: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1557:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1558:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1559: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1560: double *lsurv, *lpop, *tpop;
                   1561: 
1.231     brouard  1562: #define FD 1; /* Fixed dummy covariate */
                   1563: #define FQ 2; /* Fixed quantitative covariate */
                   1564: #define FP 3; /* Fixed product covariate */
                   1565: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1566: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1567: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1568: #define VD 10; /* Varying dummy covariate */
                   1569: #define VQ 11; /* Varying quantitative covariate */
                   1570: #define VP 12; /* Varying product covariate */
                   1571: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1572: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1573: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1574: #define APFD 16; /* Age product * fixed dummy covariate */
                   1575: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1576: #define APVD 18; /* Age product * varying dummy covariate */
                   1577: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1578: 
                   1579: #define FTYPE 1; /* Fixed covariate */
                   1580: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1581: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1582: 
                   1583: struct kmodel{
                   1584:        int maintype; /* main type */
                   1585:        int subtype; /* subtype */
                   1586: };
                   1587: struct kmodel modell[NCOVMAX];
                   1588: 
1.143     brouard  1589: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1590: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1591: 
                   1592: /**************** split *************************/
                   1593: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1594: {
                   1595:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1596:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1597:   */ 
                   1598:   char *ss;                            /* pointer */
1.186     brouard  1599:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1600: 
                   1601:   l1 = strlen(path );                  /* length of path */
                   1602:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1603:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1604:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1605:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1606:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1607:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1608:     /* get current working directory */
                   1609:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1610: #ifdef WIN32
                   1611:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1612: #else
                   1613:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1614: #endif
1.126     brouard  1615:       return( GLOCK_ERROR_GETCWD );
                   1616:     }
                   1617:     /* got dirc from getcwd*/
                   1618:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1619:   } else {                             /* strip directory from path */
1.126     brouard  1620:     ss++;                              /* after this, the filename */
                   1621:     l2 = strlen( ss );                 /* length of filename */
                   1622:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1623:     strcpy( name, ss );                /* save file name */
                   1624:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1625:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1626:     printf(" DIRC2 = %s \n",dirc);
                   1627:   }
                   1628:   /* We add a separator at the end of dirc if not exists */
                   1629:   l1 = strlen( dirc );                 /* length of directory */
                   1630:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1631:     dirc[l1] =  DIRSEPARATOR;
                   1632:     dirc[l1+1] = 0; 
                   1633:     printf(" DIRC3 = %s \n",dirc);
                   1634:   }
                   1635:   ss = strrchr( name, '.' );           /* find last / */
                   1636:   if (ss >0){
                   1637:     ss++;
                   1638:     strcpy(ext,ss);                    /* save extension */
                   1639:     l1= strlen( name);
                   1640:     l2= strlen(ss)+1;
                   1641:     strncpy( finame, name, l1-l2);
                   1642:     finame[l1-l2]= 0;
                   1643:   }
                   1644: 
                   1645:   return( 0 );                         /* we're done */
                   1646: }
                   1647: 
                   1648: 
                   1649: /******************************************/
                   1650: 
                   1651: void replace_back_to_slash(char *s, char*t)
                   1652: {
                   1653:   int i;
                   1654:   int lg=0;
                   1655:   i=0;
                   1656:   lg=strlen(t);
                   1657:   for(i=0; i<= lg; i++) {
                   1658:     (s[i] = t[i]);
                   1659:     if (t[i]== '\\') s[i]='/';
                   1660:   }
                   1661: }
                   1662: 
1.132     brouard  1663: char *trimbb(char *out, char *in)
1.137     brouard  1664: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1665:   char *s;
                   1666:   s=out;
                   1667:   while (*in != '\0'){
1.137     brouard  1668:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1669:       in++;
                   1670:     }
                   1671:     *out++ = *in++;
                   1672:   }
                   1673:   *out='\0';
                   1674:   return s;
                   1675: }
                   1676: 
1.187     brouard  1677: /* char *substrchaine(char *out, char *in, char *chain) */
                   1678: /* { */
                   1679: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1680: /*   char *s, *t; */
                   1681: /*   t=in;s=out; */
                   1682: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1683: /*     *out++ = *in++; */
                   1684: /*   } */
                   1685: 
                   1686: /*   /\* *in matches *chain *\/ */
                   1687: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1688: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1689: /*   } */
                   1690: /*   in--; chain--; */
                   1691: /*   while ( (*in != '\0')){ */
                   1692: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1693: /*     *out++ = *in++; */
                   1694: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1695: /*   } */
                   1696: /*   *out='\0'; */
                   1697: /*   out=s; */
                   1698: /*   return out; */
                   1699: /* } */
                   1700: char *substrchaine(char *out, char *in, char *chain)
                   1701: {
                   1702:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1703:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1704: 
                   1705:   char *strloc;
                   1706: 
                   1707:   strcpy (out, in); 
                   1708:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1709:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1710:   if(strloc != NULL){ 
                   1711:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1712:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1713:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1714:   }
                   1715:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1716:   return out;
                   1717: }
                   1718: 
                   1719: 
1.145     brouard  1720: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1721: {
1.187     brouard  1722:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1723:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1724:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1725:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1726:   */
1.160     brouard  1727:   char *s, *t;
1.145     brouard  1728:   t=in;s=in;
                   1729:   while ((*in != occ) && (*in != '\0')){
                   1730:     *alocc++ = *in++;
                   1731:   }
                   1732:   if( *in == occ){
                   1733:     *(alocc)='\0';
                   1734:     s=++in;
                   1735:   }
                   1736:  
                   1737:   if (s == t) {/* occ not found */
                   1738:     *(alocc-(in-s))='\0';
                   1739:     in=s;
                   1740:   }
                   1741:   while ( *in != '\0'){
                   1742:     *blocc++ = *in++;
                   1743:   }
                   1744: 
                   1745:   *blocc='\0';
                   1746:   return t;
                   1747: }
1.137     brouard  1748: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1749: {
1.187     brouard  1750:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1751:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1752:      gives blocc="abcdef2ghi" and alocc="j".
                   1753:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1754:   */
                   1755:   char *s, *t;
                   1756:   t=in;s=in;
                   1757:   while (*in != '\0'){
                   1758:     while( *in == occ){
                   1759:       *blocc++ = *in++;
                   1760:       s=in;
                   1761:     }
                   1762:     *blocc++ = *in++;
                   1763:   }
                   1764:   if (s == t) /* occ not found */
                   1765:     *(blocc-(in-s))='\0';
                   1766:   else
                   1767:     *(blocc-(in-s)-1)='\0';
                   1768:   in=s;
                   1769:   while ( *in != '\0'){
                   1770:     *alocc++ = *in++;
                   1771:   }
                   1772: 
                   1773:   *alocc='\0';
                   1774:   return s;
                   1775: }
                   1776: 
1.126     brouard  1777: int nbocc(char *s, char occ)
                   1778: {
                   1779:   int i,j=0;
                   1780:   int lg=20;
                   1781:   i=0;
                   1782:   lg=strlen(s);
                   1783:   for(i=0; i<= lg; i++) {
1.234     brouard  1784:     if  (s[i] == occ ) j++;
1.126     brouard  1785:   }
                   1786:   return j;
                   1787: }
                   1788: 
1.137     brouard  1789: /* void cutv(char *u,char *v, char*t, char occ) */
                   1790: /* { */
                   1791: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1792: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1793: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1794: /*   int i,lg,j,p=0; */
                   1795: /*   i=0; */
                   1796: /*   lg=strlen(t); */
                   1797: /*   for(j=0; j<=lg-1; j++) { */
                   1798: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1799: /*   } */
1.126     brouard  1800: 
1.137     brouard  1801: /*   for(j=0; j<p; j++) { */
                   1802: /*     (u[j] = t[j]); */
                   1803: /*   } */
                   1804: /*      u[p]='\0'; */
1.126     brouard  1805: 
1.137     brouard  1806: /*    for(j=0; j<= lg; j++) { */
                   1807: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1808: /*   } */
                   1809: /* } */
1.126     brouard  1810: 
1.160     brouard  1811: #ifdef _WIN32
                   1812: char * strsep(char **pp, const char *delim)
                   1813: {
                   1814:   char *p, *q;
                   1815:          
                   1816:   if ((p = *pp) == NULL)
                   1817:     return 0;
                   1818:   if ((q = strpbrk (p, delim)) != NULL)
                   1819:   {
                   1820:     *pp = q + 1;
                   1821:     *q = '\0';
                   1822:   }
                   1823:   else
                   1824:     *pp = 0;
                   1825:   return p;
                   1826: }
                   1827: #endif
                   1828: 
1.126     brouard  1829: /********************** nrerror ********************/
                   1830: 
                   1831: void nrerror(char error_text[])
                   1832: {
                   1833:   fprintf(stderr,"ERREUR ...\n");
                   1834:   fprintf(stderr,"%s\n",error_text);
                   1835:   exit(EXIT_FAILURE);
                   1836: }
                   1837: /*********************** vector *******************/
                   1838: double *vector(int nl, int nh)
                   1839: {
                   1840:   double *v;
                   1841:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1842:   if (!v) nrerror("allocation failure in vector");
                   1843:   return v-nl+NR_END;
                   1844: }
                   1845: 
                   1846: /************************ free vector ******************/
                   1847: void free_vector(double*v, int nl, int nh)
                   1848: {
                   1849:   free((FREE_ARG)(v+nl-NR_END));
                   1850: }
                   1851: 
                   1852: /************************ivector *******************************/
                   1853: int *ivector(long nl,long nh)
                   1854: {
                   1855:   int *v;
                   1856:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1857:   if (!v) nrerror("allocation failure in ivector");
                   1858:   return v-nl+NR_END;
                   1859: }
                   1860: 
                   1861: /******************free ivector **************************/
                   1862: void free_ivector(int *v, long nl, long nh)
                   1863: {
                   1864:   free((FREE_ARG)(v+nl-NR_END));
                   1865: }
                   1866: 
                   1867: /************************lvector *******************************/
                   1868: long *lvector(long nl,long nh)
                   1869: {
                   1870:   long *v;
                   1871:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1872:   if (!v) nrerror("allocation failure in ivector");
                   1873:   return v-nl+NR_END;
                   1874: }
                   1875: 
                   1876: /******************free lvector **************************/
                   1877: void free_lvector(long *v, long nl, long nh)
                   1878: {
                   1879:   free((FREE_ARG)(v+nl-NR_END));
                   1880: }
                   1881: 
                   1882: /******************* imatrix *******************************/
                   1883: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1884:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1885: { 
                   1886:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1887:   int **m; 
                   1888:   
                   1889:   /* allocate pointers to rows */ 
                   1890:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1891:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1892:   m += NR_END; 
                   1893:   m -= nrl; 
                   1894:   
                   1895:   
                   1896:   /* allocate rows and set pointers to them */ 
                   1897:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1898:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1899:   m[nrl] += NR_END; 
                   1900:   m[nrl] -= ncl; 
                   1901:   
                   1902:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1903:   
                   1904:   /* return pointer to array of pointers to rows */ 
                   1905:   return m; 
                   1906: } 
                   1907: 
                   1908: /****************** free_imatrix *************************/
                   1909: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1910:       int **m;
                   1911:       long nch,ncl,nrh,nrl; 
                   1912:      /* free an int matrix allocated by imatrix() */ 
                   1913: { 
                   1914:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1915:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1916: } 
                   1917: 
                   1918: /******************* matrix *******************************/
                   1919: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1920: {
                   1921:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1922:   double **m;
                   1923: 
                   1924:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1925:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1926:   m += NR_END;
                   1927:   m -= nrl;
                   1928: 
                   1929:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1930:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1931:   m[nrl] += NR_END;
                   1932:   m[nrl] -= ncl;
                   1933: 
                   1934:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1935:   return m;
1.145     brouard  1936:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1937: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1938: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1939:    */
                   1940: }
                   1941: 
                   1942: /*************************free matrix ************************/
                   1943: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1944: {
                   1945:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1946:   free((FREE_ARG)(m+nrl-NR_END));
                   1947: }
                   1948: 
                   1949: /******************* ma3x *******************************/
                   1950: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1951: {
                   1952:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1953:   double ***m;
                   1954: 
                   1955:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1956:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1957:   m += NR_END;
                   1958:   m -= nrl;
                   1959: 
                   1960:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1961:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1962:   m[nrl] += NR_END;
                   1963:   m[nrl] -= ncl;
                   1964: 
                   1965:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1966: 
                   1967:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1968:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1969:   m[nrl][ncl] += NR_END;
                   1970:   m[nrl][ncl] -= nll;
                   1971:   for (j=ncl+1; j<=nch; j++) 
                   1972:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1973:   
                   1974:   for (i=nrl+1; i<=nrh; i++) {
                   1975:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1976:     for (j=ncl+1; j<=nch; j++) 
                   1977:       m[i][j]=m[i][j-1]+nlay;
                   1978:   }
                   1979:   return m; 
                   1980:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1981:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1982:   */
                   1983: }
                   1984: 
                   1985: /*************************free ma3x ************************/
                   1986: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1987: {
                   1988:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1989:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1990:   free((FREE_ARG)(m+nrl-NR_END));
                   1991: }
                   1992: 
                   1993: /*************** function subdirf ***********/
                   1994: char *subdirf(char fileres[])
                   1995: {
                   1996:   /* Caution optionfilefiname is hidden */
                   1997:   strcpy(tmpout,optionfilefiname);
                   1998:   strcat(tmpout,"/"); /* Add to the right */
                   1999:   strcat(tmpout,fileres);
                   2000:   return tmpout;
                   2001: }
                   2002: 
                   2003: /*************** function subdirf2 ***********/
                   2004: char *subdirf2(char fileres[], char *preop)
                   2005: {
1.314     brouard  2006:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2007:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2008:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2009:   /* Caution optionfilefiname is hidden */
                   2010:   strcpy(tmpout,optionfilefiname);
                   2011:   strcat(tmpout,"/");
                   2012:   strcat(tmpout,preop);
                   2013:   strcat(tmpout,fileres);
                   2014:   return tmpout;
                   2015: }
                   2016: 
                   2017: /*************** function subdirf3 ***********/
                   2018: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2019: {
                   2020:   
                   2021:   /* Caution optionfilefiname is hidden */
                   2022:   strcpy(tmpout,optionfilefiname);
                   2023:   strcat(tmpout,"/");
                   2024:   strcat(tmpout,preop);
                   2025:   strcat(tmpout,preop2);
                   2026:   strcat(tmpout,fileres);
                   2027:   return tmpout;
                   2028: }
1.213     brouard  2029:  
                   2030: /*************** function subdirfext ***********/
                   2031: char *subdirfext(char fileres[], char *preop, char *postop)
                   2032: {
                   2033:   
                   2034:   strcpy(tmpout,preop);
                   2035:   strcat(tmpout,fileres);
                   2036:   strcat(tmpout,postop);
                   2037:   return tmpout;
                   2038: }
1.126     brouard  2039: 
1.213     brouard  2040: /*************** function subdirfext3 ***********/
                   2041: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2042: {
                   2043:   
                   2044:   /* Caution optionfilefiname is hidden */
                   2045:   strcpy(tmpout,optionfilefiname);
                   2046:   strcat(tmpout,"/");
                   2047:   strcat(tmpout,preop);
                   2048:   strcat(tmpout,fileres);
                   2049:   strcat(tmpout,postop);
                   2050:   return tmpout;
                   2051: }
                   2052:  
1.162     brouard  2053: char *asc_diff_time(long time_sec, char ascdiff[])
                   2054: {
                   2055:   long sec_left, days, hours, minutes;
                   2056:   days = (time_sec) / (60*60*24);
                   2057:   sec_left = (time_sec) % (60*60*24);
                   2058:   hours = (sec_left) / (60*60) ;
                   2059:   sec_left = (sec_left) %(60*60);
                   2060:   minutes = (sec_left) /60;
                   2061:   sec_left = (sec_left) % (60);
                   2062:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2063:   return ascdiff;
                   2064: }
                   2065: 
1.126     brouard  2066: /***************** f1dim *************************/
                   2067: extern int ncom; 
                   2068: extern double *pcom,*xicom;
                   2069: extern double (*nrfunc)(double []); 
                   2070:  
                   2071: double f1dim(double x) 
                   2072: { 
                   2073:   int j; 
                   2074:   double f;
                   2075:   double *xt; 
                   2076:  
                   2077:   xt=vector(1,ncom); 
                   2078:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2079:   f=(*nrfunc)(xt); 
                   2080:   free_vector(xt,1,ncom); 
                   2081:   return f; 
                   2082: } 
                   2083: 
                   2084: /*****************brent *************************/
                   2085: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2086: {
                   2087:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2088:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2089:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2090:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2091:    * returned function value. 
                   2092:   */
1.126     brouard  2093:   int iter; 
                   2094:   double a,b,d,etemp;
1.159     brouard  2095:   double fu=0,fv,fw,fx;
1.164     brouard  2096:   double ftemp=0.;
1.126     brouard  2097:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2098:   double e=0.0; 
                   2099:  
                   2100:   a=(ax < cx ? ax : cx); 
                   2101:   b=(ax > cx ? ax : cx); 
                   2102:   x=w=v=bx; 
                   2103:   fw=fv=fx=(*f)(x); 
                   2104:   for (iter=1;iter<=ITMAX;iter++) { 
                   2105:     xm=0.5*(a+b); 
                   2106:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2107:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2108:     printf(".");fflush(stdout);
                   2109:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2110: #ifdef DEBUGBRENT
1.126     brouard  2111:     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);
                   2112:     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);
                   2113:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2114: #endif
                   2115:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2116:       *xmin=x; 
                   2117:       return fx; 
                   2118:     } 
                   2119:     ftemp=fu;
                   2120:     if (fabs(e) > tol1) { 
                   2121:       r=(x-w)*(fx-fv); 
                   2122:       q=(x-v)*(fx-fw); 
                   2123:       p=(x-v)*q-(x-w)*r; 
                   2124:       q=2.0*(q-r); 
                   2125:       if (q > 0.0) p = -p; 
                   2126:       q=fabs(q); 
                   2127:       etemp=e; 
                   2128:       e=d; 
                   2129:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2130:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2131:       else { 
1.224     brouard  2132:                                d=p/q; 
                   2133:                                u=x+d; 
                   2134:                                if (u-a < tol2 || b-u < tol2) 
                   2135:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2136:       } 
                   2137:     } else { 
                   2138:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2139:     } 
                   2140:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2141:     fu=(*f)(u); 
                   2142:     if (fu <= fx) { 
                   2143:       if (u >= x) a=x; else b=x; 
                   2144:       SHFT(v,w,x,u) 
1.183     brouard  2145:       SHFT(fv,fw,fx,fu) 
                   2146:     } else { 
                   2147:       if (u < x) a=u; else b=u; 
                   2148:       if (fu <= fw || w == x) { 
1.224     brouard  2149:                                v=w; 
                   2150:                                w=u; 
                   2151:                                fv=fw; 
                   2152:                                fw=fu; 
1.183     brouard  2153:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2154:                                v=u; 
                   2155:                                fv=fu; 
1.183     brouard  2156:       } 
                   2157:     } 
1.126     brouard  2158:   } 
                   2159:   nrerror("Too many iterations in brent"); 
                   2160:   *xmin=x; 
                   2161:   return fx; 
                   2162: } 
                   2163: 
                   2164: /****************** mnbrak ***********************/
                   2165: 
                   2166: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2167:            double (*func)(double)) 
1.183     brouard  2168: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2169: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2170: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2171: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2172:    */
1.126     brouard  2173:   double ulim,u,r,q, dum;
                   2174:   double fu; 
1.187     brouard  2175: 
                   2176:   double scale=10.;
                   2177:   int iterscale=0;
                   2178: 
                   2179:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2180:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2181: 
                   2182: 
                   2183:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2184:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2185:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2186:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2187:   /* } */
                   2188: 
1.126     brouard  2189:   if (*fb > *fa) { 
                   2190:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2191:     SHFT(dum,*fb,*fa,dum) 
                   2192:   } 
1.126     brouard  2193:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2194:   *fc=(*func)(*cx); 
1.183     brouard  2195: #ifdef DEBUG
1.224     brouard  2196:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2197:   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  2198: #endif
1.224     brouard  2199:   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  2200:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2201:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2202:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2203:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2204:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2205:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2206:       fu=(*func)(u); 
1.163     brouard  2207: #ifdef DEBUG
                   2208:       /* f(x)=A(x-u)**2+f(u) */
                   2209:       double A, fparabu; 
                   2210:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2211:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2212:       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);
                   2213:       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  2214:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2215:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2216:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2217:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2218: #endif 
1.184     brouard  2219: #ifdef MNBRAKORIGINAL
1.183     brouard  2220: #else
1.191     brouard  2221: /*       if (fu > *fc) { */
                   2222: /* #ifdef DEBUG */
                   2223: /*       printf("mnbrak4  fu > fc \n"); */
                   2224: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2225: /* #endif */
                   2226: /*     /\* 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 *\\/  *\/ */
                   2227: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2228: /*     dum=u; /\* Shifting c and u *\/ */
                   2229: /*     u = *cx; */
                   2230: /*     *cx = dum; */
                   2231: /*     dum = fu; */
                   2232: /*     fu = *fc; */
                   2233: /*     *fc =dum; */
                   2234: /*       } else { /\* end *\/ */
                   2235: /* #ifdef DEBUG */
                   2236: /*       printf("mnbrak3  fu < fc \n"); */
                   2237: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2238: /* #endif */
                   2239: /*     dum=u; /\* Shifting c and u *\/ */
                   2240: /*     u = *cx; */
                   2241: /*     *cx = dum; */
                   2242: /*     dum = fu; */
                   2243: /*     fu = *fc; */
                   2244: /*     *fc =dum; */
                   2245: /*       } */
1.224     brouard  2246: #ifdef DEBUGMNBRAK
                   2247:                 double A, fparabu; 
                   2248:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2249:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2250:      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);
                   2251:      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  2252: #endif
1.191     brouard  2253:       dum=u; /* Shifting c and u */
                   2254:       u = *cx;
                   2255:       *cx = dum;
                   2256:       dum = fu;
                   2257:       fu = *fc;
                   2258:       *fc =dum;
1.183     brouard  2259: #endif
1.162     brouard  2260:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2261: #ifdef DEBUG
1.224     brouard  2262:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2263:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2264: #endif
1.126     brouard  2265:       fu=(*func)(u); 
                   2266:       if (fu < *fc) { 
1.183     brouard  2267: #ifdef DEBUG
1.224     brouard  2268:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2269:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2270: #endif
                   2271:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2272:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2273: #ifdef DEBUG
                   2274:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2275: #endif
                   2276:       } 
1.162     brouard  2277:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2278: #ifdef DEBUG
1.224     brouard  2279:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2280:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2281: #endif
1.126     brouard  2282:       u=ulim; 
                   2283:       fu=(*func)(u); 
1.183     brouard  2284:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2285: #ifdef DEBUG
1.224     brouard  2286:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2287:       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  2288: #endif
1.126     brouard  2289:       u=(*cx)+GOLD*(*cx-*bx); 
                   2290:       fu=(*func)(u); 
1.224     brouard  2291: #ifdef DEBUG
                   2292:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2293:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2294: #endif
1.183     brouard  2295:     } /* end tests */
1.126     brouard  2296:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2297:     SHFT(*fa,*fb,*fc,fu) 
                   2298: #ifdef DEBUG
1.224     brouard  2299:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2300:       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  2301: #endif
                   2302:   } /* 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  2303: } 
                   2304: 
                   2305: /*************** linmin ************************/
1.162     brouard  2306: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2307: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2308: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2309: the value of func at the returned location p . This is actually all accomplished by calling the
                   2310: routines mnbrak and brent .*/
1.126     brouard  2311: int ncom; 
                   2312: double *pcom,*xicom;
                   2313: double (*nrfunc)(double []); 
                   2314:  
1.224     brouard  2315: #ifdef LINMINORIGINAL
1.126     brouard  2316: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2317: #else
                   2318: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2319: #endif
1.126     brouard  2320: { 
                   2321:   double brent(double ax, double bx, double cx, 
                   2322:               double (*f)(double), double tol, double *xmin); 
                   2323:   double f1dim(double x); 
                   2324:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2325:              double *fc, double (*func)(double)); 
                   2326:   int j; 
                   2327:   double xx,xmin,bx,ax; 
                   2328:   double fx,fb,fa;
1.187     brouard  2329: 
1.203     brouard  2330: #ifdef LINMINORIGINAL
                   2331: #else
                   2332:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2333: #endif
                   2334:   
1.126     brouard  2335:   ncom=n; 
                   2336:   pcom=vector(1,n); 
                   2337:   xicom=vector(1,n); 
                   2338:   nrfunc=func; 
                   2339:   for (j=1;j<=n;j++) { 
                   2340:     pcom[j]=p[j]; 
1.202     brouard  2341:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2342:   } 
1.187     brouard  2343: 
1.203     brouard  2344: #ifdef LINMINORIGINAL
                   2345:   xx=1.;
                   2346: #else
                   2347:   axs=0.0;
                   2348:   xxs=1.;
                   2349:   do{
                   2350:     xx= xxs;
                   2351: #endif
1.187     brouard  2352:     ax=0.;
                   2353:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2354:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2355:     /* 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))   */
                   2356:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2357:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2358:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2359:     /* 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  2360: #ifdef LINMINORIGINAL
                   2361: #else
                   2362:     if (fx != fx){
1.224     brouard  2363:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2364:                        printf("|");
                   2365:                        fprintf(ficlog,"|");
1.203     brouard  2366: #ifdef DEBUGLINMIN
1.224     brouard  2367:                        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  2368: #endif
                   2369:     }
1.224     brouard  2370:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2371: #endif
                   2372:   
1.191     brouard  2373: #ifdef DEBUGLINMIN
                   2374:   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  2375:   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  2376: #endif
1.224     brouard  2377: #ifdef LINMINORIGINAL
                   2378: #else
1.317     brouard  2379:   if(fb == fx){ /* Flat function in the direction */
                   2380:     xmin=xx;
1.224     brouard  2381:     *flat=1;
1.317     brouard  2382:   }else{
1.224     brouard  2383:     *flat=0;
                   2384: #endif
                   2385:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2386:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2387:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2388:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2389:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2390:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2391: #ifdef DEBUG
1.224     brouard  2392:   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);
                   2393:   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);
                   2394: #endif
                   2395: #ifdef LINMINORIGINAL
                   2396: #else
                   2397:                        }
1.126     brouard  2398: #endif
1.191     brouard  2399: #ifdef DEBUGLINMIN
                   2400:   printf("linmin end ");
1.202     brouard  2401:   fprintf(ficlog,"linmin end ");
1.191     brouard  2402: #endif
1.126     brouard  2403:   for (j=1;j<=n;j++) { 
1.203     brouard  2404: #ifdef LINMINORIGINAL
                   2405:     xi[j] *= xmin; 
                   2406: #else
                   2407: #ifdef DEBUGLINMIN
                   2408:     if(xxs <1.0)
                   2409:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2410: #endif
                   2411:     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) */
                   2412: #ifdef DEBUGLINMIN
                   2413:     if(xxs <1.0)
                   2414:       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 );
                   2415: #endif
                   2416: #endif
1.187     brouard  2417:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2418:   } 
1.191     brouard  2419: #ifdef DEBUGLINMIN
1.203     brouard  2420:   printf("\n");
1.191     brouard  2421:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2422:   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  2423:   for (j=1;j<=n;j++) { 
1.202     brouard  2424:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2425:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2426:     if(j % ncovmodel == 0){
1.191     brouard  2427:       printf("\n");
1.202     brouard  2428:       fprintf(ficlog,"\n");
                   2429:     }
1.191     brouard  2430:   }
1.203     brouard  2431: #else
1.191     brouard  2432: #endif
1.126     brouard  2433:   free_vector(xicom,1,n); 
                   2434:   free_vector(pcom,1,n); 
                   2435: } 
                   2436: 
                   2437: 
                   2438: /*************** powell ************************/
1.162     brouard  2439: /*
1.317     brouard  2440: Minimization of a function func of n variables. Input consists in an initial starting point
                   2441: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2442: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2443: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2444: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2445: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2446:  */
1.224     brouard  2447: #ifdef LINMINORIGINAL
                   2448: #else
                   2449:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2450:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2451: #endif
1.126     brouard  2452: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2453:            double (*func)(double [])) 
                   2454: { 
1.224     brouard  2455: #ifdef LINMINORIGINAL
                   2456:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2457:              double (*func)(double [])); 
1.224     brouard  2458: #else 
1.241     brouard  2459:  void linmin(double p[], double xi[], int n, double *fret,
                   2460:             double (*func)(double []),int *flat); 
1.224     brouard  2461: #endif
1.239     brouard  2462:  int i,ibig,j,jk,k; 
1.126     brouard  2463:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2464:   double directest;
1.126     brouard  2465:   double fp,fptt;
                   2466:   double *xits;
                   2467:   int niterf, itmp;
                   2468: 
                   2469:   pt=vector(1,n); 
                   2470:   ptt=vector(1,n); 
                   2471:   xit=vector(1,n); 
                   2472:   xits=vector(1,n); 
                   2473:   *fret=(*func)(p); 
                   2474:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2475:   rcurr_time = time(NULL);  
1.126     brouard  2476:   for (*iter=1;;++(*iter)) { 
                   2477:     ibig=0; 
                   2478:     del=0.0; 
1.157     brouard  2479:     rlast_time=rcurr_time;
                   2480:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2481:     rcurr_time = time(NULL);  
                   2482:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2483:     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);
                   2484:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2485: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2486:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2487:     for (i=1;i<=n;i++) {
1.126     brouard  2488:       fprintf(ficrespow," %.12lf", p[i]);
                   2489:     }
1.239     brouard  2490:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2491:     printf("\n#model=  1      +     age ");
                   2492:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2493:     if(nagesqr==1){
1.241     brouard  2494:        printf("  + age*age  ");
                   2495:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2496:     }
                   2497:     for(j=1;j <=ncovmodel-2;j++){
                   2498:       if(Typevar[j]==0) {
                   2499:        printf("  +      V%d  ",Tvar[j]);
                   2500:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2501:       }else if(Typevar[j]==1) {
                   2502:        printf("  +    V%d*age ",Tvar[j]);
                   2503:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2504:       }else if(Typevar[j]==2) {
                   2505:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2506:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2507:       }
                   2508:     }
1.126     brouard  2509:     printf("\n");
1.239     brouard  2510: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2511: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2512:     fprintf(ficlog,"\n");
1.239     brouard  2513:     for(i=1,jk=1; i <=nlstate; i++){
                   2514:       for(k=1; k <=(nlstate+ndeath); k++){
                   2515:        if (k != i) {
                   2516:          printf("%d%d ",i,k);
                   2517:          fprintf(ficlog,"%d%d ",i,k);
                   2518:          for(j=1; j <=ncovmodel; j++){
                   2519:            printf("%12.7f ",p[jk]);
                   2520:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2521:            jk++; 
                   2522:          }
                   2523:          printf("\n");
                   2524:          fprintf(ficlog,"\n");
                   2525:        }
                   2526:       }
                   2527:     }
1.241     brouard  2528:     if(*iter <=3 && *iter >1){
1.157     brouard  2529:       tml = *localtime(&rcurr_time);
                   2530:       strcpy(strcurr,asctime(&tml));
                   2531:       rforecast_time=rcurr_time; 
1.126     brouard  2532:       itmp = strlen(strcurr);
                   2533:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2534:        strcurr[itmp-1]='\0';
1.162     brouard  2535:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2536:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2537:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2538:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2539:        forecast_time = *localtime(&rforecast_time);
                   2540:        strcpy(strfor,asctime(&forecast_time));
                   2541:        itmp = strlen(strfor);
                   2542:        if(strfor[itmp-1]=='\n')
                   2543:          strfor[itmp-1]='\0';
                   2544:        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);
                   2545:        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  2546:       }
                   2547:     }
1.187     brouard  2548:     for (i=1;i<=n;i++) { /* For each direction i */
                   2549:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2550:       fptt=(*fret); 
                   2551: #ifdef DEBUG
1.203     brouard  2552:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2553:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2554: #endif
1.203     brouard  2555:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2556:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2557: #ifdef LINMINORIGINAL
1.188     brouard  2558:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2559: #else
                   2560:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2561:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2562: #endif
                   2563:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2564:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2565:                                /* because that direction will be replaced unless the gain del is small */
                   2566:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2567:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2568:                                /* with the new direction. */
                   2569:                                del=fabs(fptt-(*fret)); 
                   2570:                                ibig=i; 
1.126     brouard  2571:       } 
                   2572: #ifdef DEBUG
                   2573:       printf("%d %.12e",i,(*fret));
                   2574:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2575:       for (j=1;j<=n;j++) {
1.224     brouard  2576:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2577:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2578:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2579:       }
                   2580:       for(j=1;j<=n;j++) {
1.225     brouard  2581:                                printf(" p(%d)=%.12e",j,p[j]);
                   2582:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2583:       }
                   2584:       printf("\n");
                   2585:       fprintf(ficlog,"\n");
                   2586: #endif
1.187     brouard  2587:     } /* end loop on each direction i */
                   2588:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2589:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2590:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2591:     for(j=1;j<=n;j++) {
                   2592:       if(flatdir[j] >0){
                   2593:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2594:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2595:       }
1.319     brouard  2596:       /* printf("\n"); */
                   2597:       /* fprintf(ficlog,"\n"); */
                   2598:     }
1.243     brouard  2599:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2600:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2601:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2602:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2603:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2604:       /* decreased of more than 3.84  */
                   2605:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2606:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2607:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2608:                        
1.188     brouard  2609:       /* Starting the program with initial values given by a former maximization will simply change */
                   2610:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2611:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2612:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2613: #ifdef DEBUG
                   2614:       int k[2],l;
                   2615:       k[0]=1;
                   2616:       k[1]=-1;
                   2617:       printf("Max: %.12e",(*func)(p));
                   2618:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2619:       for (j=1;j<=n;j++) {
                   2620:        printf(" %.12e",p[j]);
                   2621:        fprintf(ficlog," %.12e",p[j]);
                   2622:       }
                   2623:       printf("\n");
                   2624:       fprintf(ficlog,"\n");
                   2625:       for(l=0;l<=1;l++) {
                   2626:        for (j=1;j<=n;j++) {
                   2627:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2628:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2629:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2630:        }
                   2631:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2632:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2633:       }
                   2634: #endif
                   2635: 
                   2636:       free_vector(xit,1,n); 
                   2637:       free_vector(xits,1,n); 
                   2638:       free_vector(ptt,1,n); 
                   2639:       free_vector(pt,1,n); 
                   2640:       return; 
1.192     brouard  2641:     } /* enough precision */ 
1.240     brouard  2642:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2643:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2644:       ptt[j]=2.0*p[j]-pt[j]; 
                   2645:       xit[j]=p[j]-pt[j]; 
                   2646:       pt[j]=p[j]; 
                   2647:     } 
1.181     brouard  2648:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2649: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2650:                if (*iter <=4) {
1.225     brouard  2651: #else
                   2652: #endif
1.224     brouard  2653: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2654: #else
1.161     brouard  2655:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2656: #endif
1.162     brouard  2657:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2658:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2659:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2660:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2661:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2662:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2663:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2664:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2665:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2666:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2667:       /* mu² and del² are equal when f3=f1 */
                   2668:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2669:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2670:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2671:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2672: #ifdef NRCORIGINAL
                   2673:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2674: #else
                   2675:       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  2676:       t= t- del*SQR(fp-fptt);
1.183     brouard  2677: #endif
1.202     brouard  2678:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2679: #ifdef DEBUG
1.181     brouard  2680:       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);
                   2681:       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  2682:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2683:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2684:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2685:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2686:       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);
                   2687:       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);
                   2688: #endif
1.183     brouard  2689: #ifdef POWELLORIGINAL
                   2690:       if (t < 0.0) { /* Then we use it for new direction */
                   2691: #else
1.182     brouard  2692:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2693:                                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  2694:         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  2695:         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  2696:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2697:       } 
1.181     brouard  2698:       if (directest < 0.0) { /* Then we use it for new direction */
                   2699: #endif
1.191     brouard  2700: #ifdef DEBUGLINMIN
1.234     brouard  2701:        printf("Before linmin in direction P%d-P0\n",n);
                   2702:        for (j=1;j<=n;j++) {
                   2703:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2704:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2705:          if(j % ncovmodel == 0){
                   2706:            printf("\n");
                   2707:            fprintf(ficlog,"\n");
                   2708:          }
                   2709:        }
1.224     brouard  2710: #endif
                   2711: #ifdef LINMINORIGINAL
1.234     brouard  2712:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2713: #else
1.234     brouard  2714:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2715:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2716: #endif
1.234     brouard  2717:        
1.191     brouard  2718: #ifdef DEBUGLINMIN
1.234     brouard  2719:        for (j=1;j<=n;j++) { 
                   2720:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2721:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2722:          if(j % ncovmodel == 0){
                   2723:            printf("\n");
                   2724:            fprintf(ficlog,"\n");
                   2725:          }
                   2726:        }
1.224     brouard  2727: #endif
1.234     brouard  2728:        for (j=1;j<=n;j++) { 
                   2729:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2730:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2731:        }
1.224     brouard  2732: #ifdef LINMINORIGINAL
                   2733: #else
1.234     brouard  2734:        for (j=1, flatd=0;j<=n;j++) {
                   2735:          if(flatdir[j]>0)
                   2736:            flatd++;
                   2737:        }
                   2738:        if(flatd >0){
1.255     brouard  2739:          printf("%d flat directions: ",flatd);
                   2740:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2741:          for (j=1;j<=n;j++) { 
                   2742:            if(flatdir[j]>0){
                   2743:              printf("%d ",j);
                   2744:              fprintf(ficlog,"%d ",j);
                   2745:            }
                   2746:          }
                   2747:          printf("\n");
                   2748:          fprintf(ficlog,"\n");
1.319     brouard  2749: #ifdef FLATSUP
                   2750:           free_vector(xit,1,n); 
                   2751:           free_vector(xits,1,n); 
                   2752:           free_vector(ptt,1,n); 
                   2753:           free_vector(pt,1,n); 
                   2754:           return;
                   2755: #endif
1.234     brouard  2756:        }
1.191     brouard  2757: #endif
1.234     brouard  2758:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2759:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2760:        
1.126     brouard  2761: #ifdef DEBUG
1.234     brouard  2762:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2763:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2764:        for(j=1;j<=n;j++){
                   2765:          printf(" %lf",xit[j]);
                   2766:          fprintf(ficlog," %lf",xit[j]);
                   2767:        }
                   2768:        printf("\n");
                   2769:        fprintf(ficlog,"\n");
1.126     brouard  2770: #endif
1.192     brouard  2771:       } /* end of t or directest negative */
1.224     brouard  2772: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2773: #else
1.234     brouard  2774:       } /* end if (fptt < fp)  */
1.192     brouard  2775: #endif
1.225     brouard  2776: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2777:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2778: #else
1.224     brouard  2779: #endif
1.234     brouard  2780:                } /* loop iteration */ 
1.126     brouard  2781: } 
1.234     brouard  2782:   
1.126     brouard  2783: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2784:   
1.235     brouard  2785:   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  2786:   {
1.279     brouard  2787:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2788:      *   (and selected quantitative values in nres)
                   2789:      *  by left multiplying the unit
                   2790:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2791:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2792:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2793:      * or prevalence in state 1, prevalence in state 2, 0
                   2794:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2795:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2796:      * Output is prlim.
                   2797:      * Initial matrix pimij 
                   2798:      */
1.206     brouard  2799:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2800:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2801:   /*  0,                   0                  , 1} */
                   2802:   /*
                   2803:    * and after some iteration: */
                   2804:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2805:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2806:   /*  0,                   0                  , 1} */
                   2807:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2808:   /* {0.51571254859325999, 0.4842874514067399, */
                   2809:   /*  0.51326036147820708, 0.48673963852179264} */
                   2810:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2811:     
1.332     brouard  2812:     int i, ii,j,k, k1;
1.209     brouard  2813:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2814:   /* double **matprod2(); */ /* test */
1.218     brouard  2815:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2816:   double **newm;
1.209     brouard  2817:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2818:   int ncvloop=0;
1.288     brouard  2819:   int first=0;
1.169     brouard  2820:   
1.209     brouard  2821:   min=vector(1,nlstate);
                   2822:   max=vector(1,nlstate);
                   2823:   meandiff=vector(1,nlstate);
                   2824: 
1.218     brouard  2825:        /* Starting with matrix unity */
1.126     brouard  2826:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2827:     for (j=1;j<=nlstate+ndeath;j++){
                   2828:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2829:     }
1.169     brouard  2830:   
                   2831:   cov[1]=1.;
                   2832:   
                   2833:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2834:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2835:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2836:     ncvloop++;
1.126     brouard  2837:     newm=savm;
                   2838:     /* Covariates have to be included here again */
1.138     brouard  2839:     cov[2]=agefin;
1.319     brouard  2840:      if(nagesqr==1){
                   2841:       cov[3]= agefin*agefin;
                   2842:      }
1.332     brouard  2843:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2844:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2845:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2846:        if(Typevar[k1]==1){ /* A product with age */
                   2847:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2848:        }else{
                   2849:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2850:        }
                   2851:      }/* End of loop on model equation */
                   2852:      
                   2853: /* Start of old code (replaced by a loop on position in the model equation */
                   2854:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2855:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2856:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2857:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2858:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2859:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2860:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2861:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2862:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2863:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2864:     /*    *nsd=3                              (1)  (2)           (3) */
                   2865:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2866:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2867:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2868:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2869:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2870:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2871:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2872:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2873:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2874:     /*    *TvarsDpType */
                   2875:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2876:     /*    * nsd=1              (1)           (2) */
                   2877:     /*    *TvarsD[nsd]          3             2 */
                   2878:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2879:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2880:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2881:     /*    *\/ */
                   2882:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2883:     /*   /\* 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)); *\/ */
                   2884:     /* } */
                   2885:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2886:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2887:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2888:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2889:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2890:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2891:     /*   /\* 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]); *\/ */
                   2892:     /* } */
                   2893:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2894:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2895:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2896:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2897:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2898:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2899:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2900:     /*   } */
                   2901:     /*   /\* 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]); *\/ */
                   2902:     /* } */
                   2903:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2904:     /*   /\* 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]); *\/ */
                   2905:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2906:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2907:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2908:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2909:     /*         }else{ */
                   2910:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2911:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2912:     /*         } */
                   2913:     /*   }else{ */
                   2914:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2915:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2916:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2917:     /*         }else{ */
                   2918:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2919:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2920:     /*         } */
                   2921:     /*   } */
                   2922:     /* } /\* End product without age *\/ */
                   2923: /* ENd of old code */
1.138     brouard  2924:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2925:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2926:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2927:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2928:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2929:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2930:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2931:     
1.126     brouard  2932:     savm=oldm;
                   2933:     oldm=newm;
1.209     brouard  2934: 
                   2935:     for(j=1; j<=nlstate; j++){
                   2936:       max[j]=0.;
                   2937:       min[j]=1.;
                   2938:     }
                   2939:     for(i=1;i<=nlstate;i++){
                   2940:       sumnew=0;
                   2941:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2942:       for(j=1; j<=nlstate; j++){ 
                   2943:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2944:        max[j]=FMAX(max[j],prlim[i][j]);
                   2945:        min[j]=FMIN(min[j],prlim[i][j]);
                   2946:       }
                   2947:     }
                   2948: 
1.126     brouard  2949:     maxmax=0.;
1.209     brouard  2950:     for(j=1; j<=nlstate; j++){
                   2951:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2952:       maxmax=FMAX(maxmax,meandiff[j]);
                   2953:       /* 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  2954:     } /* j loop */
1.203     brouard  2955:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2956:     /* 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  2957:     if(maxmax < ftolpl){
1.209     brouard  2958:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2959:       free_vector(min,1,nlstate);
                   2960:       free_vector(max,1,nlstate);
                   2961:       free_vector(meandiff,1,nlstate);
1.126     brouard  2962:       return prlim;
                   2963:     }
1.288     brouard  2964:   } /* agefin loop */
1.208     brouard  2965:     /* After some age loop it doesn't converge */
1.288     brouard  2966:   if(!first){
                   2967:     first=1;
                   2968:     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  2969:     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);
                   2970:   }else if (first >=1 && first <10){
                   2971:     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);
                   2972:     first++;
                   2973:   }else if (first ==10){
                   2974:     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);
                   2975:     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");
                   2976:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2977:     first++;
1.288     brouard  2978:   }
                   2979: 
1.209     brouard  2980:   /* 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); */
                   2981:   free_vector(min,1,nlstate);
                   2982:   free_vector(max,1,nlstate);
                   2983:   free_vector(meandiff,1,nlstate);
1.208     brouard  2984:   
1.169     brouard  2985:   return prlim; /* should not reach here */
1.126     brouard  2986: }
                   2987: 
1.217     brouard  2988: 
                   2989:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2990: 
1.218     brouard  2991:  /* 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) */
                   2992:  /* 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  2993:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2994: {
1.264     brouard  2995:   /* 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  2996:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2997:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2998:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2999:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3000:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3001:   /* Initial matrix pimij */
                   3002:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3003:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3004:   /*  0,                   0                  , 1} */
                   3005:   /*
                   3006:    * and after some iteration: */
                   3007:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3008:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3009:   /*  0,                   0                  , 1} */
                   3010:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3011:   /* {0.51571254859325999, 0.4842874514067399, */
                   3012:   /*  0.51326036147820708, 0.48673963852179264} */
                   3013:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3014: 
1.332     brouard  3015:   int i, ii,j,k, k1;
1.247     brouard  3016:   int first=0;
1.217     brouard  3017:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3018:   /* double **matprod2(); */ /* test */
                   3019:   double **out, cov[NCOVMAX+1], **bmij();
                   3020:   double **newm;
1.218     brouard  3021:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3022:   double        **oldm, **savm;  /* for use */
                   3023: 
1.217     brouard  3024:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3025:   int ncvloop=0;
                   3026:   
                   3027:   min=vector(1,nlstate);
                   3028:   max=vector(1,nlstate);
                   3029:   meandiff=vector(1,nlstate);
                   3030: 
1.266     brouard  3031:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3032:   oldm=oldms; savm=savms;
                   3033:   
                   3034:   /* Starting with matrix unity */
                   3035:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3036:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3037:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3038:     }
                   3039:   
                   3040:   cov[1]=1.;
                   3041:   
                   3042:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3043:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3044:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3045:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3046:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3047:     ncvloop++;
1.218     brouard  3048:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3049:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3050:     /* Covariates have to be included here again */
                   3051:     cov[2]=agefin;
1.319     brouard  3052:     if(nagesqr==1){
1.217     brouard  3053:       cov[3]= agefin*agefin;;
1.319     brouard  3054:     }
1.332     brouard  3055:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3056:       if(Typevar[k1]==1){ /* A product with age */
                   3057:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3058:       }else{
1.332     brouard  3059:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3060:       }
1.332     brouard  3061:     }/* End of loop on model equation */
                   3062: 
                   3063: /* Old code */ 
                   3064: 
                   3065:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3066:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3067:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3068:     /*   /\* 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)); *\/ */
                   3069:     /* } */
                   3070:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3071:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3072:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3073:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3074:     /* /\* } *\/ */
                   3075:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3076:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3077:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3078:     /*   /\* 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]); *\/ */
                   3079:     /* } */
                   3080:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3081:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3082:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3083:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3084:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3085:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3086:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3087:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3088:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3089:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3090:     /*   } */
                   3091:     /*   /\* 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]); *\/ */
                   3092:     /* } */
                   3093:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3094:     /*   /\* 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]); *\/ */
                   3095:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3096:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3097:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3098:     /*         }else{ */
                   3099:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3100:     /*         } */
                   3101:     /*   }else{ */
                   3102:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3103:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3104:     /*         }else{ */
                   3105:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3106:     /*         } */
                   3107:     /*   } */
                   3108:     /* } */
1.217     brouard  3109:     
                   3110:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3111:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3112:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3113:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3114:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3115:                /* ij should be linked to the correct index of cov */
                   3116:                /* age and covariate values ij are in 'cov', but we need to pass
                   3117:                 * ij for the observed prevalence at age and status and covariate
                   3118:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3119:                 */
                   3120:     /* 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 *\/ */
                   3121:     /* 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 *\/ */
                   3122:     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  3123:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3124:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3125:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3126:     /*         printf("%d newm= ",i); */
                   3127:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3128:     /*           printf("%f ",newm[i][j]); */
                   3129:     /*         } */
                   3130:     /*         printf("oldm * "); */
                   3131:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3132:     /*           printf("%f ",oldm[i][j]); */
                   3133:     /*         } */
1.268     brouard  3134:     /*         printf(" bmmij "); */
1.266     brouard  3135:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3136:     /*           printf("%f ",pmmij[i][j]); */
                   3137:     /*         } */
                   3138:     /*         printf("\n"); */
                   3139:     /*   } */
                   3140:     /* } */
1.217     brouard  3141:     savm=oldm;
                   3142:     oldm=newm;
1.266     brouard  3143: 
1.217     brouard  3144:     for(j=1; j<=nlstate; j++){
                   3145:       max[j]=0.;
                   3146:       min[j]=1.;
                   3147:     }
                   3148:     for(j=1; j<=nlstate; j++){ 
                   3149:       for(i=1;i<=nlstate;i++){
1.234     brouard  3150:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3151:        bprlim[i][j]= newm[i][j];
                   3152:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3153:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3154:       }
                   3155:     }
1.218     brouard  3156:                
1.217     brouard  3157:     maxmax=0.;
                   3158:     for(i=1; i<=nlstate; i++){
1.318     brouard  3159:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3160:       maxmax=FMAX(maxmax,meandiff[i]);
                   3161:       /* 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  3162:     } /* i loop */
1.217     brouard  3163:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3164:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3165:     if(maxmax < ftolpl){
1.220     brouard  3166:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3167:       free_vector(min,1,nlstate);
                   3168:       free_vector(max,1,nlstate);
                   3169:       free_vector(meandiff,1,nlstate);
                   3170:       return bprlim;
                   3171:     }
1.288     brouard  3172:   } /* agefin loop */
1.217     brouard  3173:     /* After some age loop it doesn't converge */
1.288     brouard  3174:   if(!first){
1.247     brouard  3175:     first=1;
                   3176:     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\
                   3177: 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);
                   3178:   }
                   3179:   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  3180: 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);
                   3181:   /* 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); */
                   3182:   free_vector(min,1,nlstate);
                   3183:   free_vector(max,1,nlstate);
                   3184:   free_vector(meandiff,1,nlstate);
                   3185:   
                   3186:   return bprlim; /* should not reach here */
                   3187: }
                   3188: 
1.126     brouard  3189: /*************** transition probabilities ***************/ 
                   3190: 
                   3191: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3192: {
1.138     brouard  3193:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3194:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3195:      model to the ncovmodel covariates (including constant and age).
                   3196:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3197:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3198:      ncth covariate in the global vector x is given by the formula:
                   3199:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3200:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3201:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3202:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3203:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3204:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3205:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3206:   */
                   3207:   double s1, lnpijopii;
1.126     brouard  3208:   /*double t34;*/
1.164     brouard  3209:   int i,j, nc, ii, jj;
1.126     brouard  3210: 
1.223     brouard  3211:   for(i=1; i<= nlstate; i++){
                   3212:     for(j=1; j<i;j++){
                   3213:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3214:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3215:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3216:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3217:       }
                   3218:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3219:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3220:     }
                   3221:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3222:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3223:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3224:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3225:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3226:       }
                   3227:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3228:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3229:     }
                   3230:   }
1.218     brouard  3231:   
1.223     brouard  3232:   for(i=1; i<= nlstate; i++){
                   3233:     s1=0;
                   3234:     for(j=1; j<i; j++){
                   3235:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3236:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1.223     brouard  3237:     }
                   3238:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3239:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3240:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1.223     brouard  3241:     }
                   3242:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3243:     ps[i][i]=1./(s1+1.);
                   3244:     /* Computing other pijs */
                   3245:     for(j=1; j<i; j++)
1.325     brouard  3246:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3247:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3248:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3249:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3250:   } /* end i */
1.218     brouard  3251:   
1.223     brouard  3252:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3253:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3254:       ps[ii][jj]=0;
                   3255:       ps[ii][ii]=1;
                   3256:     }
                   3257:   }
1.294     brouard  3258: 
                   3259: 
1.223     brouard  3260:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3261:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3262:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3263:   /*   } */
                   3264:   /*   printf("\n "); */
                   3265:   /* } */
                   3266:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3267:   /*
                   3268:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3269:                goto end;*/
1.266     brouard  3270:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3271: }
                   3272: 
1.218     brouard  3273: /*************** backward transition probabilities ***************/ 
                   3274: 
                   3275:  /* 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 ) */
                   3276: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3277:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3278: {
1.302     brouard  3279:   /* 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  3280:    * 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  3281:    */
1.218     brouard  3282:   int i, ii, j,k;
1.222     brouard  3283:   
                   3284:   double **out, **pmij();
                   3285:   double sumnew=0.;
1.218     brouard  3286:   double agefin;
1.292     brouard  3287:   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  3288:   double **dnewm, **dsavm, **doldm;
                   3289:   double **bbmij;
                   3290:   
1.218     brouard  3291:   doldm=ddoldms; /* global pointers */
1.222     brouard  3292:   dnewm=ddnewms;
                   3293:   dsavm=ddsavms;
1.318     brouard  3294: 
                   3295:   /* Debug */
                   3296:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3297:   agefin=cov[2];
1.268     brouard  3298:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3299:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3300:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3301:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3302: 
                   3303:   /* P_x */
1.325     brouard  3304:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3305:   /* outputs pmmij which is a stochastic matrix in row */
                   3306: 
                   3307:   /* Diag(w_x) */
1.292     brouard  3308:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3309:   sumnew=0.;
1.269     brouard  3310:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3311:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3312:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3313:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3314:   }
                   3315:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3316:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3317:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3318:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3319:     }
                   3320:   }else{
                   3321:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3322:       for (j=1;j<=nlstate+ndeath;j++)
                   3323:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3324:     }
                   3325:     /* if(sumnew <0.9){ */
                   3326:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3327:     /* } */
                   3328:   }
                   3329:   k3=0.0;  /* We put the last diagonal to 0 */
                   3330:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3331:       doldm[ii][ii]= k3;
                   3332:   }
                   3333:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3334:   
1.292     brouard  3335:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3336:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3337: 
1.292     brouard  3338:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3339:   /* 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  3340:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3341:     sumnew=0.;
1.222     brouard  3342:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3343:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3344:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3345:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3346:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3347:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3348:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3349:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3350:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3351:        /* }else */
1.268     brouard  3352:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3353:     } /*End ii */
                   3354:   } /* 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 */
                   3355: 
1.292     brouard  3356:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3357:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3358:   /* end bmij */
1.266     brouard  3359:   return ps; /*pointer is unchanged */
1.218     brouard  3360: }
1.217     brouard  3361: /*************** transition probabilities ***************/ 
                   3362: 
1.218     brouard  3363: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3364: {
                   3365:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3366:      computes the probability to be observed in state j being in state i by appying the
                   3367:      model to the ncovmodel covariates (including constant and age).
                   3368:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3369:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3370:      ncth covariate in the global vector x is given by the formula:
                   3371:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3372:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3373:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3374:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3375:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3376:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3377:   */
                   3378:   double s1, lnpijopii;
                   3379:   /*double t34;*/
                   3380:   int i,j, nc, ii, jj;
                   3381: 
1.234     brouard  3382:   for(i=1; i<= nlstate; i++){
                   3383:     for(j=1; j<i;j++){
                   3384:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3385:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3386:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3387:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3388:       }
                   3389:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3390:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3391:     }
                   3392:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3393:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3394:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3395:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3396:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3397:       }
                   3398:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3399:     }
                   3400:   }
                   3401:   
                   3402:   for(i=1; i<= nlstate; i++){
                   3403:     s1=0;
                   3404:     for(j=1; j<i; j++){
                   3405:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3406:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3407:     }
                   3408:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3409:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3410:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3411:     }
                   3412:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3413:     ps[i][i]=1./(s1+1.);
                   3414:     /* Computing other pijs */
                   3415:     for(j=1; j<i; j++)
                   3416:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3417:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3418:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3419:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3420:   } /* end i */
                   3421:   
                   3422:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3423:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3424:       ps[ii][jj]=0;
                   3425:       ps[ii][ii]=1;
                   3426:     }
                   3427:   }
1.296     brouard  3428:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3429:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3430:     s1=0.;
                   3431:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3432:       s1+=ps[ii][jj];
                   3433:     }
                   3434:     for(ii=1; ii<= nlstate; ii++){
                   3435:       ps[ii][jj]=ps[ii][jj]/s1;
                   3436:     }
                   3437:   }
                   3438:   /* Transposition */
                   3439:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3440:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3441:       s1=ps[ii][jj];
                   3442:       ps[ii][jj]=ps[jj][ii];
                   3443:       ps[jj][ii]=s1;
                   3444:     }
                   3445:   }
                   3446:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3447:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3448:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3449:   /*   } */
                   3450:   /*   printf("\n "); */
                   3451:   /* } */
                   3452:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3453:   /*
                   3454:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3455:     goto end;*/
                   3456:   return ps;
1.217     brouard  3457: }
                   3458: 
                   3459: 
1.126     brouard  3460: /**************** Product of 2 matrices ******************/
                   3461: 
1.145     brouard  3462: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3463: {
                   3464:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3465:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3466:   /* in, b, out are matrice of pointers which should have been initialized 
                   3467:      before: only the contents of out is modified. The function returns
                   3468:      a pointer to pointers identical to out */
1.145     brouard  3469:   int i, j, k;
1.126     brouard  3470:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3471:     for(k=ncolol; k<=ncoloh; k++){
                   3472:       out[i][k]=0.;
                   3473:       for(j=ncl; j<=nch; j++)
                   3474:        out[i][k] +=in[i][j]*b[j][k];
                   3475:     }
1.126     brouard  3476:   return out;
                   3477: }
                   3478: 
                   3479: 
                   3480: /************* Higher Matrix Product ***************/
                   3481: 
1.235     brouard  3482: 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  3483: {
1.332     brouard  3484:   /* 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  3485:      'nhstepm*hstepm*stepm' months (i.e. until
                   3486:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3487:      nhstepm*hstepm matrices. 
                   3488:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3489:      (typically every 2 years instead of every month which is too big 
                   3490:      for the memory).
                   3491:      Model is determined by parameters x and covariates have to be 
                   3492:      included manually here. 
                   3493: 
                   3494:      */
                   3495: 
1.330     brouard  3496:   int i, j, d, h, k, k1;
1.131     brouard  3497:   double **out, cov[NCOVMAX+1];
1.126     brouard  3498:   double **newm;
1.187     brouard  3499:   double agexact;
1.214     brouard  3500:   double agebegin, ageend;
1.126     brouard  3501: 
                   3502:   /* Hstepm could be zero and should return the unit matrix */
                   3503:   for (i=1;i<=nlstate+ndeath;i++)
                   3504:     for (j=1;j<=nlstate+ndeath;j++){
                   3505:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3506:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3507:     }
                   3508:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3509:   for(h=1; h <=nhstepm; h++){
                   3510:     for(d=1; d <=hstepm; d++){
                   3511:       newm=savm;
                   3512:       /* Covariates have to be included here again */
                   3513:       cov[1]=1.;
1.214     brouard  3514:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3515:       cov[2]=agexact;
1.319     brouard  3516:       if(nagesqr==1){
1.227     brouard  3517:        cov[3]= agexact*agexact;
1.319     brouard  3518:       }
1.330     brouard  3519:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3520:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3521:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3522:        if(Typevar[k1]==1){ /* A product with age */
                   3523:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3524:        }else{
                   3525:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3526:        }
                   3527:       }/* End of loop on model equation */
                   3528:        /* Old code */ 
                   3529: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3530: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3531: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3532: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3533: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3534: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3535: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3536: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3537: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3538: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3539: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3540: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3541: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3542: /*       /\* 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]])); *\/ */
                   3543: /*       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); */
                   3544: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3545: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3546: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3547: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3548: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3549: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3550: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3551: /*       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]]); */
                   3552: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3553: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3554: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3555: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3556: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3557: /*       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]); */
                   3558: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3559: 
                   3560: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3561: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3562: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3563: /*       /\* *\/ */
1.330     brouard  3564: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3565: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3566: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3567: /* /\*cptcovage=2                   1               2      *\/ */
                   3568: /* /\*Tage[k]=                      5               8      *\/  */
                   3569: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3570: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3571: /*       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]]); */
                   3572: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3573: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3574: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3575: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3576: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3577: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3578: /*       /\*   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); *\/ */
                   3579: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3580: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3581: /*       /\* } *\/ */
                   3582: /*       /\* 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]); *\/ */
                   3583: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3584: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3585: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3586: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3587: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3588: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3589: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3590: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3591: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3592:          
1.332     brouard  3593: /*       /\* 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])]); *\/ */
                   3594: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3595: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3596: /*       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]]); */
                   3597: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3598: 
                   3599: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3600: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3601: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3602: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3603: /*           /\* 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]])]; *\/ */
                   3604: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3605: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3606: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3607: /*       /\*   } *\/ */
                   3608: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3609: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3610: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3611: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3612: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3613: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3614: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3615: /*       /\*   } *\/ */
                   3616: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3617: /*     }/\*end of products *\/ */
                   3618:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3619:       /* for (k=1; k<=cptcovn;k++)  */
                   3620:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3621:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3622:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3623:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3624:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3625:       
                   3626:       
1.126     brouard  3627:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3628:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3629:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3630:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3631:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3632:       /* if((int)age == 70){ */
                   3633:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3634:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3635:       /*         printf("%d pmmij ",i); */
                   3636:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3637:       /*           printf("%f ",pmmij[i][j]); */
                   3638:       /*         } */
                   3639:       /*         printf(" oldm "); */
                   3640:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3641:       /*           printf("%f ",oldm[i][j]); */
                   3642:       /*         } */
                   3643:       /*         printf("\n"); */
                   3644:       /*       } */
                   3645:       /* } */
1.126     brouard  3646:       savm=oldm;
                   3647:       oldm=newm;
                   3648:     }
                   3649:     for(i=1; i<=nlstate+ndeath; i++)
                   3650:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3651:        po[i][j][h]=newm[i][j];
                   3652:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3653:       }
1.128     brouard  3654:     /*printf("h=%d ",h);*/
1.126     brouard  3655:   } /* end h */
1.267     brouard  3656:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3657:   return po;
                   3658: }
                   3659: 
1.217     brouard  3660: /************* Higher Back Matrix Product ***************/
1.218     brouard  3661: /* 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  3662: 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  3663: {
1.332     brouard  3664:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3665:      computes the transition matrix starting at age 'age' over
1.217     brouard  3666:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3667:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3668:      nhstepm*hstepm matrices.
                   3669:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3670:      (typically every 2 years instead of every month which is too big
1.217     brouard  3671:      for the memory).
1.218     brouard  3672:      Model is determined by parameters x and covariates have to be
1.266     brouard  3673:      included manually here. Then we use a call to bmij(x and cov)
                   3674:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3675:   */
1.217     brouard  3676: 
1.332     brouard  3677:   int i, j, d, h, k, k1;
1.266     brouard  3678:   double **out, cov[NCOVMAX+1], **bmij();
                   3679:   double **newm, ***newmm;
1.217     brouard  3680:   double agexact;
                   3681:   double agebegin, ageend;
1.222     brouard  3682:   double **oldm, **savm;
1.217     brouard  3683: 
1.266     brouard  3684:   newmm=po; /* To be saved */
                   3685:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3686:   /* Hstepm could be zero and should return the unit matrix */
                   3687:   for (i=1;i<=nlstate+ndeath;i++)
                   3688:     for (j=1;j<=nlstate+ndeath;j++){
                   3689:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3690:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3691:     }
                   3692:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3693:   for(h=1; h <=nhstepm; h++){
                   3694:     for(d=1; d <=hstepm; d++){
                   3695:       newm=savm;
                   3696:       /* Covariates have to be included here again */
                   3697:       cov[1]=1.;
1.271     brouard  3698:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3699:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3700:         /* Debug */
                   3701:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3702:       cov[2]=agexact;
1.332     brouard  3703:       if(nagesqr==1){
1.222     brouard  3704:        cov[3]= agexact*agexact;
1.332     brouard  3705:       }
                   3706:       /** New code */
                   3707:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3708:        if(Typevar[k1]==1){ /* A product with age */
                   3709:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3710:        }else{
1.332     brouard  3711:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3712:        }
1.332     brouard  3713:       }/* End of loop on model equation */
                   3714:       /** End of new code */
                   3715:   /** This was old code */
                   3716:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3717:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3718:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3719:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3720:       /*   /\* 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)); *\/ */
                   3721:       /* } */
                   3722:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3723:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3724:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3725:       /*       /\* 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]); *\/ */
                   3726:       /* } */
                   3727:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3728:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3729:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3730:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3731:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3732:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3733:       /*       } */
                   3734:       /*       /\* 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]); *\/ */
                   3735:       /* } */
                   3736:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3737:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3738:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3739:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3740:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3741:       /*         }else{ */
                   3742:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3743:       /*         } */
                   3744:       /*       }else{ */
                   3745:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3746:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3747:       /*         }else{ */
                   3748:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3749:       /*         } */
                   3750:       /*       } */
                   3751:       /* }                      */
                   3752:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3753:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3754: /** End of old code */
                   3755:       
1.218     brouard  3756:       /* Careful transposed matrix */
1.266     brouard  3757:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3758:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3759:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3760:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3761:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3762:       /* if((int)age == 70){ */
                   3763:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3764:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3765:       /*         printf("%d pmmij ",i); */
                   3766:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3767:       /*           printf("%f ",pmmij[i][j]); */
                   3768:       /*         } */
                   3769:       /*         printf(" oldm "); */
                   3770:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3771:       /*           printf("%f ",oldm[i][j]); */
                   3772:       /*         } */
                   3773:       /*         printf("\n"); */
                   3774:       /*       } */
                   3775:       /* } */
                   3776:       savm=oldm;
                   3777:       oldm=newm;
                   3778:     }
                   3779:     for(i=1; i<=nlstate+ndeath; i++)
                   3780:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3781:        po[i][j][h]=newm[i][j];
1.268     brouard  3782:        /* if(h==nhstepm) */
                   3783:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3784:       }
1.268     brouard  3785:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3786:   } /* end h */
1.268     brouard  3787:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3788:   return po;
                   3789: }
                   3790: 
                   3791: 
1.162     brouard  3792: #ifdef NLOPT
                   3793:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3794:   double fret;
                   3795:   double *xt;
                   3796:   int j;
                   3797:   myfunc_data *d2 = (myfunc_data *) pd;
                   3798: /* xt = (p1-1); */
                   3799:   xt=vector(1,n); 
                   3800:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3801: 
                   3802:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3803:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3804:   printf("Function = %.12lf ",fret);
                   3805:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3806:   printf("\n");
                   3807:  free_vector(xt,1,n);
                   3808:   return fret;
                   3809: }
                   3810: #endif
1.126     brouard  3811: 
                   3812: /*************** log-likelihood *************/
                   3813: double func( double *x)
                   3814: {
1.226     brouard  3815:   int i, ii, j, k, mi, d, kk;
                   3816:   int ioffset=0;
                   3817:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3818:   double **out;
                   3819:   double lli; /* Individual log likelihood */
                   3820:   int s1, s2;
1.228     brouard  3821:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.226     brouard  3822:   double bbh, survp;
                   3823:   long ipmx;
                   3824:   double agexact;
                   3825:   /*extern weight */
                   3826:   /* We are differentiating ll according to initial status */
                   3827:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3828:   /*for(i=1;i<imx;i++) 
                   3829:     printf(" %d\n",s[4][i]);
                   3830:   */
1.162     brouard  3831: 
1.226     brouard  3832:   ++countcallfunc;
1.162     brouard  3833: 
1.226     brouard  3834:   cov[1]=1.;
1.126     brouard  3835: 
1.226     brouard  3836:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3837:   ioffset=0;
1.226     brouard  3838:   if(mle==1){
                   3839:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3840:       /* Computes the values of the ncovmodel covariates of the model
                   3841:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3842:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3843:         to be observed in j being in i according to the model.
                   3844:       */
1.243     brouard  3845:       ioffset=2+nagesqr ;
1.233     brouard  3846:    /* Fixed */
1.319     brouard  3847:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3848:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3849:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3850:        /*  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  3851:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3852:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
                   3853:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3854:       }
1.226     brouard  3855:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3856:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3857:         has been calculated etc */
                   3858:       /* For an individual i, wav[i] gives the number of effective waves */
                   3859:       /* We compute the contribution to Likelihood of each effective transition
                   3860:         mw[mi][i] is real wave of the mi th effectve wave */
                   3861:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3862:         s2=s[mw[mi+1][i]][i];
                   3863:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3864:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3865:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3866:       */
                   3867:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3868:        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*/
                   3869:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3870:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3871:        }
                   3872:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3873:          for (j=1;j<=nlstate+ndeath;j++){
                   3874:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3875:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3876:          }
                   3877:        for(d=0; d<dh[mi][i]; d++){
                   3878:          newm=savm;
                   3879:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3880:          cov[2]=agexact;
                   3881:          if(nagesqr==1)
                   3882:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3883:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3884:            if(!FixedV[Tvar[Tage[kk]]])
                   3885:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3886:            else
                   3887:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3888:          }
                   3889:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3890:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3891:          savm=oldm;
                   3892:          oldm=newm;
                   3893:        } /* end mult */
                   3894:        
                   3895:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3896:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3897:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3898:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3899:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3900:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3901:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3902:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3903:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3904:                                 * -stepm/2 to stepm/2 .
                   3905:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3906:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3907:                                 */
1.234     brouard  3908:        s1=s[mw[mi][i]][i];
                   3909:        s2=s[mw[mi+1][i]][i];
                   3910:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3911:        /* bias bh is positive if real duration
                   3912:         * is higher than the multiple of stepm and negative otherwise.
                   3913:         */
                   3914:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3915:        if( s2 > nlstate){ 
                   3916:          /* i.e. if s2 is a death state and if the date of death is known 
                   3917:             then the contribution to the likelihood is the probability to 
                   3918:             die between last step unit time and current  step unit time, 
                   3919:             which is also equal to probability to die before dh 
                   3920:             minus probability to die before dh-stepm . 
                   3921:             In version up to 0.92 likelihood was computed
                   3922:             as if date of death was unknown. Death was treated as any other
                   3923:             health state: the date of the interview describes the actual state
                   3924:             and not the date of a change in health state. The former idea was
                   3925:             to consider that at each interview the state was recorded
                   3926:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3927:             introduced the exact date of death then we should have modified
                   3928:             the contribution of an exact death to the likelihood. This new
                   3929:             contribution is smaller and very dependent of the step unit
                   3930:             stepm. It is no more the probability to die between last interview
                   3931:             and month of death but the probability to survive from last
                   3932:             interview up to one month before death multiplied by the
                   3933:             probability to die within a month. Thanks to Chris
                   3934:             Jackson for correcting this bug.  Former versions increased
                   3935:             mortality artificially. The bad side is that we add another loop
                   3936:             which slows down the processing. The difference can be up to 10%
                   3937:             lower mortality.
                   3938:          */
                   3939:          /* If, at the beginning of the maximization mostly, the
                   3940:             cumulative probability or probability to be dead is
                   3941:             constant (ie = 1) over time d, the difference is equal to
                   3942:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3943:             s1 at precedent wave, to be dead a month before current
                   3944:             wave is equal to probability, being at state s1 at
                   3945:             precedent wave, to be dead at mont of the current
                   3946:             wave. Then the observed probability (that this person died)
                   3947:             is null according to current estimated parameter. In fact,
                   3948:             it should be very low but not zero otherwise the log go to
                   3949:             infinity.
                   3950:          */
1.183     brouard  3951: /* #ifdef INFINITYORIGINAL */
                   3952: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3953: /* #else */
                   3954: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3955: /*         lli=log(mytinydouble); */
                   3956: /*       else */
                   3957: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3958: /* #endif */
1.226     brouard  3959:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3960:          
1.226     brouard  3961:        } else if  ( s2==-1 ) { /* alive */
                   3962:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3963:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3964:          /*survp += out[s1][j]; */
                   3965:          lli= log(survp);
                   3966:        }
                   3967:        else if  (s2==-4) { 
                   3968:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3969:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3970:          lli= log(survp); 
                   3971:        } 
                   3972:        else if  (s2==-5) { 
                   3973:          for (j=1,survp=0. ; j<=2; j++)  
                   3974:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3975:          lli= log(survp); 
                   3976:        } 
                   3977:        else{
                   3978:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3979:          /*  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 */
                   3980:        } 
                   3981:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3982:        /*if(lli ==000.0)*/
                   3983:        /*printf("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); */
                   3984:        ipmx +=1;
                   3985:        sw += weight[i];
                   3986:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3987:        /* if (lli < log(mytinydouble)){ */
                   3988:        /*   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); */
                   3989:        /*   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]); */
                   3990:        /* } */
                   3991:       } /* end of wave */
                   3992:     } /* end of individual */
                   3993:   }  else if(mle==2){
                   3994:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  3995:       ioffset=2+nagesqr ;
                   3996:       for (k=1; k<=ncovf;k++)
                   3997:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  3998:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3999:        for(k=1; k <= ncovv ; k++){
                   4000:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4001:        }
1.226     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:          }
                   4007:        for(d=0; d<=dh[mi][i]; d++){
                   4008:          newm=savm;
                   4009:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4010:          cov[2]=agexact;
                   4011:          if(nagesqr==1)
                   4012:            cov[3]= agexact*agexact;
                   4013:          for (kk=1; kk<=cptcovage;kk++) {
                   4014:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4015:          }
                   4016:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4017:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4018:          savm=oldm;
                   4019:          oldm=newm;
                   4020:        } /* end mult */
                   4021:       
                   4022:        s1=s[mw[mi][i]][i];
                   4023:        s2=s[mw[mi+1][i]][i];
                   4024:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4025:        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 */
                   4026:        ipmx +=1;
                   4027:        sw += weight[i];
                   4028:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4029:       } /* end of wave */
                   4030:     } /* end of individual */
                   4031:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4032:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4033:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4034:       for(mi=1; mi<= wav[i]-1; mi++){
                   4035:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4036:          for (j=1;j<=nlstate+ndeath;j++){
                   4037:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4038:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4039:          }
                   4040:        for(d=0; d<dh[mi][i]; d++){
                   4041:          newm=savm;
                   4042:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4043:          cov[2]=agexact;
                   4044:          if(nagesqr==1)
                   4045:            cov[3]= agexact*agexact;
                   4046:          for (kk=1; kk<=cptcovage;kk++) {
                   4047:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4048:          }
                   4049:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4050:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4051:          savm=oldm;
                   4052:          oldm=newm;
                   4053:        } /* end mult */
                   4054:       
                   4055:        s1=s[mw[mi][i]][i];
                   4056:        s2=s[mw[mi+1][i]][i];
                   4057:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4058:        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 */
                   4059:        ipmx +=1;
                   4060:        sw += weight[i];
                   4061:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4062:       } /* end of wave */
                   4063:     } /* end of individual */
                   4064:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4065:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4066:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4067:       for(mi=1; mi<= wav[i]-1; mi++){
                   4068:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4069:          for (j=1;j<=nlstate+ndeath;j++){
                   4070:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4071:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4072:          }
                   4073:        for(d=0; d<dh[mi][i]; d++){
                   4074:          newm=savm;
                   4075:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4076:          cov[2]=agexact;
                   4077:          if(nagesqr==1)
                   4078:            cov[3]= agexact*agexact;
                   4079:          for (kk=1; kk<=cptcovage;kk++) {
                   4080:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4081:          }
1.126     brouard  4082:        
1.226     brouard  4083:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4084:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4085:          savm=oldm;
                   4086:          oldm=newm;
                   4087:        } /* end mult */
                   4088:       
                   4089:        s1=s[mw[mi][i]][i];
                   4090:        s2=s[mw[mi+1][i]][i];
                   4091:        if( s2 > nlstate){ 
                   4092:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4093:        } else if  ( s2==-1 ) { /* alive */
                   4094:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4095:            survp += out[s1][j];
                   4096:          lli= log(survp);
                   4097:        }else{
                   4098:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4099:        }
                   4100:        ipmx +=1;
                   4101:        sw += weight[i];
                   4102:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4103: /*     printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1.226     brouard  4104:       } /* end of wave */
                   4105:     } /* end of individual */
                   4106:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4107:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4108:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4109:       for(mi=1; mi<= wav[i]-1; mi++){
                   4110:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4111:          for (j=1;j<=nlstate+ndeath;j++){
                   4112:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4113:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4114:          }
                   4115:        for(d=0; d<dh[mi][i]; d++){
                   4116:          newm=savm;
                   4117:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4118:          cov[2]=agexact;
                   4119:          if(nagesqr==1)
                   4120:            cov[3]= agexact*agexact;
                   4121:          for (kk=1; kk<=cptcovage;kk++) {
                   4122:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4123:          }
1.126     brouard  4124:        
1.226     brouard  4125:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4126:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4127:          savm=oldm;
                   4128:          oldm=newm;
                   4129:        } /* end mult */
                   4130:       
                   4131:        s1=s[mw[mi][i]][i];
                   4132:        s2=s[mw[mi+1][i]][i];
                   4133:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4134:        ipmx +=1;
                   4135:        sw += weight[i];
                   4136:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4137:        /*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]);*/
                   4138:       } /* end of wave */
                   4139:     } /* end of individual */
                   4140:   } /* End of if */
                   4141:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4142:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4143:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4144:   return -l;
1.126     brouard  4145: }
                   4146: 
                   4147: /*************** log-likelihood *************/
                   4148: double funcone( double *x)
                   4149: {
1.228     brouard  4150:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  4151:   int i, ii, j, k, mi, d, kk;
1.228     brouard  4152:   int ioffset=0;
1.131     brouard  4153:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4154:   double **out;
                   4155:   double lli; /* Individual log likelihood */
                   4156:   double llt;
                   4157:   int s1, s2;
1.228     brouard  4158:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4159: 
1.126     brouard  4160:   double bbh, survp;
1.187     brouard  4161:   double agexact;
1.214     brouard  4162:   double agebegin, ageend;
1.126     brouard  4163:   /*extern weight */
                   4164:   /* We are differentiating ll according to initial status */
                   4165:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4166:   /*for(i=1;i<imx;i++) 
                   4167:     printf(" %d\n",s[4][i]);
                   4168:   */
                   4169:   cov[1]=1.;
                   4170: 
                   4171:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4172:   ioffset=0;
                   4173:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  4174:     /* ioffset=2+nagesqr+cptcovage; */
                   4175:     ioffset=2+nagesqr;
1.232     brouard  4176:     /* Fixed */
1.224     brouard  4177:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4178:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  4179:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.232     brouard  4180:       cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
                   4181: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4182: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4183: /*    cov[2+6]=covar[2][i]; V2  */
                   4184: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4185: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4186: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4187: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4188: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4189: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4190:     }
1.232     brouard  4191:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4192:     /*   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?)*\/ */
                   4193:     /* } */
1.231     brouard  4194:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4195:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4196:     /* } */
1.225     brouard  4197:     
1.233     brouard  4198: 
                   4199:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4200:     /* Wave varying (but not age varying) */
                   4201:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4202:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4203:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4204:       }
1.232     brouard  4205:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4206:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4207:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4208:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4209:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4210:       /* 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]); */
1.232     brouard  4211:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4212:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4213:       /*       /\* 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]); *\/ */
                   4214:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4215:       /* } */
1.126     brouard  4216:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4217:        for (j=1;j<=nlstate+ndeath;j++){
                   4218:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4219:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4220:        }
1.214     brouard  4221:       
                   4222:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4223:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4224:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4225:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4226:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4227:          and mw[mi+1][i]. dh depends on stepm.*/
                   4228:        newm=savm;
1.247     brouard  4229:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4230:        cov[2]=agexact;
                   4231:        if(nagesqr==1)
                   4232:          cov[3]= agexact*agexact;
                   4233:        for (kk=1; kk<=cptcovage;kk++) {
                   4234:          if(!FixedV[Tvar[Tage[kk]]])
                   4235:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4236:          else
                   4237:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4238:        }
                   4239:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4240:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4241:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4242:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4243:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4244:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4245:        savm=oldm;
                   4246:        oldm=newm;
1.126     brouard  4247:       } /* end mult */
                   4248:       
                   4249:       s1=s[mw[mi][i]][i];
                   4250:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4251:       /* if(s2==-1){ */
1.268     brouard  4252:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4253:       /*       /\* exit(1); *\/ */
                   4254:       /* } */
1.126     brouard  4255:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4256:       /* bias is positive if real duration
                   4257:        * is higher than the multiple of stepm and negative otherwise.
                   4258:        */
                   4259:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4260:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4261:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4262:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4263:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4264:        lli= log(survp);
1.126     brouard  4265:       }else if (mle==1){
1.242     brouard  4266:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4267:       } else if(mle==2){
1.242     brouard  4268:        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  4269:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4270:        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  4271:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4272:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4273:       } else{  /* mle=0 back to 1 */
1.242     brouard  4274:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4275:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4276:       } /* End of if */
                   4277:       ipmx +=1;
                   4278:       sw += weight[i];
                   4279:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  4280:       /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1.126     brouard  4281:       if(globpr){
1.246     brouard  4282:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4283:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4284:                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  4285:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4286:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4287:          llt +=ll[k]*gipmx/gsw;
                   4288:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4289:        }
                   4290:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4291:       }
1.232     brouard  4292:        } /* end of wave */
                   4293: } /* end of individual */
                   4294: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4295: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4296: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4297: if(globpr==0){ /* First time we count the contributions and weights */
                   4298:        gipmx=ipmx;
                   4299:        gsw=sw;
                   4300: }
                   4301: return -l;
1.126     brouard  4302: }
                   4303: 
                   4304: 
                   4305: /*************** function likelione ***********/
1.292     brouard  4306: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4307: {
                   4308:   /* This routine should help understanding what is done with 
                   4309:      the selection of individuals/waves and
                   4310:      to check the exact contribution to the likelihood.
                   4311:      Plotting could be done.
                   4312:    */
                   4313:   int k;
                   4314: 
                   4315:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4316:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4317:     strcat(fileresilk,fileresu);
1.126     brouard  4318:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4319:       printf("Problem with resultfile: %s\n", fileresilk);
                   4320:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4321:     }
1.214     brouard  4322:     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");
                   4323:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4324:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4325:     for(k=1; k<=nlstate; k++) 
                   4326:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4327:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4328:   }
                   4329: 
1.292     brouard  4330:   *fretone=(*func)(p);
1.126     brouard  4331:   if(*globpri !=0){
                   4332:     fclose(ficresilk);
1.205     brouard  4333:     if (mle ==0)
                   4334:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4335:     else if(mle >=1)
                   4336:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4337:     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  4338:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4339:       
                   4340:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4341:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
1.208     brouard  4342: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4343:     }
1.207     brouard  4344:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.204     brouard  4345: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4346:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4347: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4348:     fflush(fichtm);
1.205     brouard  4349:   }
1.126     brouard  4350:   return;
                   4351: }
                   4352: 
                   4353: 
                   4354: /*********** Maximum Likelihood Estimation ***************/
                   4355: 
                   4356: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4357: {
1.319     brouard  4358:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4359:   double **xi;
                   4360:   double fret;
                   4361:   double fretone; /* Only one call to likelihood */
                   4362:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4363: 
                   4364: #ifdef NLOPT
                   4365:   int creturn;
                   4366:   nlopt_opt opt;
                   4367:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4368:   double *lb;
                   4369:   double minf; /* the minimum objective value, upon return */
                   4370:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4371:   myfunc_data dinst, *d = &dinst;
                   4372: #endif
                   4373: 
                   4374: 
1.126     brouard  4375:   xi=matrix(1,npar,1,npar);
                   4376:   for (i=1;i<=npar;i++)
                   4377:     for (j=1;j<=npar;j++)
                   4378:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4379:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4380:   strcpy(filerespow,"POW_"); 
1.126     brouard  4381:   strcat(filerespow,fileres);
                   4382:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4383:     printf("Problem with resultfile: %s\n", filerespow);
                   4384:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4385:   }
                   4386:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4387:   for (i=1;i<=nlstate;i++)
                   4388:     for(j=1;j<=nlstate+ndeath;j++)
                   4389:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4390:   fprintf(ficrespow,"\n");
1.162     brouard  4391: #ifdef POWELL
1.319     brouard  4392: #ifdef LINMINORIGINAL
                   4393: #else /* LINMINORIGINAL */
                   4394:   
                   4395:   flatdir=ivector(1,npar); 
                   4396:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4397: #endif /*LINMINORIGINAL */
                   4398: 
                   4399: #ifdef FLATSUP
                   4400:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4401:   /* reorganizing p by suppressing flat directions */
                   4402:   for(i=1, jk=1; i <=nlstate; i++){
                   4403:     for(k=1; k <=(nlstate+ndeath); k++){
                   4404:       if (k != i) {
                   4405:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4406:         if(flatdir[jk]==1){
                   4407:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4408:         }
                   4409:         for(j=1; j <=ncovmodel; j++){
                   4410:           printf("%12.7f ",p[jk]);
                   4411:           jk++; 
                   4412:         }
                   4413:         printf("\n");
                   4414:       }
                   4415:     }
                   4416:   }
                   4417: /* skipping */
                   4418:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4419:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4420:     for(k=1; k <=(nlstate+ndeath); k++){
                   4421:       if (k != i) {
                   4422:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4423:         if(flatdir[jk]==1){
                   4424:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4425:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4426:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4427:             /*q[jjk]=p[jk];*/
                   4428:           }
                   4429:         }else{
                   4430:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4431:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4432:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4433:             /*q[jjk]=p[jk];*/
                   4434:           }
                   4435:         }
                   4436:         printf("\n");
                   4437:       }
                   4438:       fflush(stdout);
                   4439:     }
                   4440:   }
                   4441:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4442: #else  /* FLATSUP */
1.126     brouard  4443:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4444: #endif  /* FLATSUP */
                   4445: 
                   4446: #ifdef LINMINORIGINAL
                   4447: #else
                   4448:       free_ivector(flatdir,1,npar); 
                   4449: #endif  /* LINMINORIGINAL*/
                   4450: #endif /* POWELL */
1.126     brouard  4451: 
1.162     brouard  4452: #ifdef NLOPT
                   4453: #ifdef NEWUOA
                   4454:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4455: #else
                   4456:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4457: #endif
                   4458:   lb=vector(0,npar-1);
                   4459:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4460:   nlopt_set_lower_bounds(opt, lb);
                   4461:   nlopt_set_initial_step1(opt, 0.1);
                   4462:   
                   4463:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4464:   d->function = func;
                   4465:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4466:   nlopt_set_min_objective(opt, myfunc, d);
                   4467:   nlopt_set_xtol_rel(opt, ftol);
                   4468:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4469:     printf("nlopt failed! %d\n",creturn); 
                   4470:   }
                   4471:   else {
                   4472:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4473:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4474:     iter=1; /* not equal */
                   4475:   }
                   4476:   nlopt_destroy(opt);
                   4477: #endif
1.319     brouard  4478: #ifdef FLATSUP
                   4479:   /* npared = npar -flatd/ncovmodel; */
                   4480:   /* xired= matrix(1,npared,1,npared); */
                   4481:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4482:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4483:   /* free_matrix(xire,1,npared,1,npared); */
                   4484: #else  /* FLATSUP */
                   4485: #endif /* FLATSUP */
1.126     brouard  4486:   free_matrix(xi,1,npar,1,npar);
                   4487:   fclose(ficrespow);
1.203     brouard  4488:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4489:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4490:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4491: 
                   4492: }
                   4493: 
                   4494: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4495: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4496: {
                   4497:   double  **a,**y,*x,pd;
1.203     brouard  4498:   /* double **hess; */
1.164     brouard  4499:   int i, j;
1.126     brouard  4500:   int *indx;
                   4501: 
                   4502:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4503:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4504:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4505:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4506:   double gompertz(double p[]);
1.203     brouard  4507:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4508: 
                   4509:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4510:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4511:   for (i=1;i<=npar;i++){
1.203     brouard  4512:     printf("%d-",i);fflush(stdout);
                   4513:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4514:    
                   4515:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4516:     
                   4517:     /*  printf(" %f ",p[i]);
                   4518:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4519:   }
                   4520:   
                   4521:   for (i=1;i<=npar;i++) {
                   4522:     for (j=1;j<=npar;j++)  {
                   4523:       if (j>i) { 
1.203     brouard  4524:        printf(".%d-%d",i,j);fflush(stdout);
                   4525:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4526:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4527:        
                   4528:        hess[j][i]=hess[i][j];    
                   4529:        /*printf(" %lf ",hess[i][j]);*/
                   4530:       }
                   4531:     }
                   4532:   }
                   4533:   printf("\n");
                   4534:   fprintf(ficlog,"\n");
                   4535: 
                   4536:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4537:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4538:   
                   4539:   a=matrix(1,npar,1,npar);
                   4540:   y=matrix(1,npar,1,npar);
                   4541:   x=vector(1,npar);
                   4542:   indx=ivector(1,npar);
                   4543:   for (i=1;i<=npar;i++)
                   4544:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4545:   ludcmp(a,npar,indx,&pd);
                   4546: 
                   4547:   for (j=1;j<=npar;j++) {
                   4548:     for (i=1;i<=npar;i++) x[i]=0;
                   4549:     x[j]=1;
                   4550:     lubksb(a,npar,indx,x);
                   4551:     for (i=1;i<=npar;i++){ 
                   4552:       matcov[i][j]=x[i];
                   4553:     }
                   4554:   }
                   4555: 
                   4556:   printf("\n#Hessian matrix#\n");
                   4557:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4558:   for (i=1;i<=npar;i++) { 
                   4559:     for (j=1;j<=npar;j++) { 
1.203     brouard  4560:       printf("%.6e ",hess[i][j]);
                   4561:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4562:     }
                   4563:     printf("\n");
                   4564:     fprintf(ficlog,"\n");
                   4565:   }
                   4566: 
1.203     brouard  4567:   /* printf("\n#Covariance matrix#\n"); */
                   4568:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4569:   /* for (i=1;i<=npar;i++) {  */
                   4570:   /*   for (j=1;j<=npar;j++) {  */
                   4571:   /*     printf("%.6e ",matcov[i][j]); */
                   4572:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4573:   /*   } */
                   4574:   /*   printf("\n"); */
                   4575:   /*   fprintf(ficlog,"\n"); */
                   4576:   /* } */
                   4577: 
1.126     brouard  4578:   /* Recompute Inverse */
1.203     brouard  4579:   /* for (i=1;i<=npar;i++) */
                   4580:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4581:   /* ludcmp(a,npar,indx,&pd); */
                   4582: 
                   4583:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4584: 
                   4585:   /* for (j=1;j<=npar;j++) { */
                   4586:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4587:   /*   x[j]=1; */
                   4588:   /*   lubksb(a,npar,indx,x); */
                   4589:   /*   for (i=1;i<=npar;i++){  */
                   4590:   /*     y[i][j]=x[i]; */
                   4591:   /*     printf("%.3e ",y[i][j]); */
                   4592:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4593:   /*   } */
                   4594:   /*   printf("\n"); */
                   4595:   /*   fprintf(ficlog,"\n"); */
                   4596:   /* } */
                   4597: 
                   4598:   /* Verifying the inverse matrix */
                   4599: #ifdef DEBUGHESS
                   4600:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4601: 
1.203     brouard  4602:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4603:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4604: 
                   4605:   for (j=1;j<=npar;j++) {
                   4606:     for (i=1;i<=npar;i++){ 
1.203     brouard  4607:       printf("%.2f ",y[i][j]);
                   4608:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4609:     }
                   4610:     printf("\n");
                   4611:     fprintf(ficlog,"\n");
                   4612:   }
1.203     brouard  4613: #endif
1.126     brouard  4614: 
                   4615:   free_matrix(a,1,npar,1,npar);
                   4616:   free_matrix(y,1,npar,1,npar);
                   4617:   free_vector(x,1,npar);
                   4618:   free_ivector(indx,1,npar);
1.203     brouard  4619:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4620: 
                   4621: 
                   4622: }
                   4623: 
                   4624: /*************** hessian matrix ****************/
                   4625: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4626: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4627:   int i;
                   4628:   int l=1, lmax=20;
1.203     brouard  4629:   double k1,k2, res, fx;
1.132     brouard  4630:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4631:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4632:   int k=0,kmax=10;
                   4633:   double l1;
                   4634: 
                   4635:   fx=func(x);
                   4636:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4637:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4638:     l1=pow(10,l);
                   4639:     delts=delt;
                   4640:     for(k=1 ; k <kmax; k=k+1){
                   4641:       delt = delta*(l1*k);
                   4642:       p2[theta]=x[theta] +delt;
1.145     brouard  4643:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4644:       p2[theta]=x[theta]-delt;
                   4645:       k2=func(p2)-fx;
                   4646:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4647:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4648:       
1.203     brouard  4649: #ifdef DEBUGHESSII
1.126     brouard  4650:       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);
                   4651:       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);
                   4652: #endif
                   4653:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4654:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4655:        k=kmax;
                   4656:       }
                   4657:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4658:        k=kmax; l=lmax*10;
1.126     brouard  4659:       }
                   4660:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4661:        delts=delt;
                   4662:       }
1.203     brouard  4663:     } /* End loop k */
1.126     brouard  4664:   }
                   4665:   delti[theta]=delts;
                   4666:   return res; 
                   4667:   
                   4668: }
                   4669: 
1.203     brouard  4670: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4671: {
                   4672:   int i;
1.164     brouard  4673:   int l=1, lmax=20;
1.126     brouard  4674:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4675:   double p2[MAXPARM+1];
1.203     brouard  4676:   int k, kmax=1;
                   4677:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4678: 
                   4679:   int firstime=0;
1.203     brouard  4680:   
1.126     brouard  4681:   fx=func(x);
1.203     brouard  4682:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4683:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4684:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4685:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4686:     k1=func(p2)-fx;
                   4687:   
1.203     brouard  4688:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4689:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4690:     k2=func(p2)-fx;
                   4691:   
1.203     brouard  4692:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4693:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4694:     k3=func(p2)-fx;
                   4695:   
1.203     brouard  4696:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4697:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4698:     k4=func(p2)-fx;
1.203     brouard  4699:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4700:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4701:       firstime=1;
1.203     brouard  4702:       kmax=kmax+10;
1.208     brouard  4703:     }
                   4704:     if(kmax >=10 || firstime ==1){
1.246     brouard  4705:       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);
                   4706:       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  4707:       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);
                   4708:       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);
                   4709:     }
                   4710: #ifdef DEBUGHESSIJ
                   4711:     v1=hess[thetai][thetai];
                   4712:     v2=hess[thetaj][thetaj];
                   4713:     cv12=res;
                   4714:     /* Computing eigen value of Hessian matrix */
                   4715:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4716:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4717:     if ((lc2 <0) || (lc1 <0) ){
                   4718:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4719:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4720:       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);
                   4721:       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);
                   4722:     }
1.126     brouard  4723: #endif
                   4724:   }
                   4725:   return res;
                   4726: }
                   4727: 
1.203     brouard  4728:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4729: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4730: /* { */
                   4731: /*   int i; */
                   4732: /*   int l=1, lmax=20; */
                   4733: /*   double k1,k2,k3,k4,res,fx; */
                   4734: /*   double p2[MAXPARM+1]; */
                   4735: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4736: /*   int k=0,kmax=10; */
                   4737: /*   double l1; */
                   4738:   
                   4739: /*   fx=func(x); */
                   4740: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4741: /*     l1=pow(10,l); */
                   4742: /*     delts=delt; */
                   4743: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4744: /*       delt = delti*(l1*k); */
                   4745: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4746: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4747: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4748: /*       k1=func(p2)-fx; */
                   4749:       
                   4750: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4751: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4752: /*       k2=func(p2)-fx; */
                   4753:       
                   4754: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4755: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4756: /*       k3=func(p2)-fx; */
                   4757:       
                   4758: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4759: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4760: /*       k4=func(p2)-fx; */
                   4761: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4762: /* #ifdef DEBUGHESSIJ */
                   4763: /*       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); */
                   4764: /*       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); */
                   4765: /* #endif */
                   4766: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4767: /*     k=kmax; */
                   4768: /*       } */
                   4769: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4770: /*     k=kmax; l=lmax*10; */
                   4771: /*       } */
                   4772: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4773: /*     delts=delt; */
                   4774: /*       } */
                   4775: /*     } /\* End loop k *\/ */
                   4776: /*   } */
                   4777: /*   delti[theta]=delts; */
                   4778: /*   return res;  */
                   4779: /* } */
                   4780: 
                   4781: 
1.126     brouard  4782: /************** Inverse of matrix **************/
                   4783: void ludcmp(double **a, int n, int *indx, double *d) 
                   4784: { 
                   4785:   int i,imax,j,k; 
                   4786:   double big,dum,sum,temp; 
                   4787:   double *vv; 
                   4788:  
                   4789:   vv=vector(1,n); 
                   4790:   *d=1.0; 
                   4791:   for (i=1;i<=n;i++) { 
                   4792:     big=0.0; 
                   4793:     for (j=1;j<=n;j++) 
                   4794:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4795:     if (big == 0.0){
                   4796:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4797:       for (j=1;j<=n;j++) {
                   4798:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4799:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4800:       }
                   4801:       fflush(ficlog);
                   4802:       fclose(ficlog);
                   4803:       nrerror("Singular matrix in routine ludcmp"); 
                   4804:     }
1.126     brouard  4805:     vv[i]=1.0/big; 
                   4806:   } 
                   4807:   for (j=1;j<=n;j++) { 
                   4808:     for (i=1;i<j;i++) { 
                   4809:       sum=a[i][j]; 
                   4810:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4811:       a[i][j]=sum; 
                   4812:     } 
                   4813:     big=0.0; 
                   4814:     for (i=j;i<=n;i++) { 
                   4815:       sum=a[i][j]; 
                   4816:       for (k=1;k<j;k++) 
                   4817:        sum -= a[i][k]*a[k][j]; 
                   4818:       a[i][j]=sum; 
                   4819:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4820:        big=dum; 
                   4821:        imax=i; 
                   4822:       } 
                   4823:     } 
                   4824:     if (j != imax) { 
                   4825:       for (k=1;k<=n;k++) { 
                   4826:        dum=a[imax][k]; 
                   4827:        a[imax][k]=a[j][k]; 
                   4828:        a[j][k]=dum; 
                   4829:       } 
                   4830:       *d = -(*d); 
                   4831:       vv[imax]=vv[j]; 
                   4832:     } 
                   4833:     indx[j]=imax; 
                   4834:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4835:     if (j != n) { 
                   4836:       dum=1.0/(a[j][j]); 
                   4837:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4838:     } 
                   4839:   } 
                   4840:   free_vector(vv,1,n);  /* Doesn't work */
                   4841: ;
                   4842: } 
                   4843: 
                   4844: void lubksb(double **a, int n, int *indx, double b[]) 
                   4845: { 
                   4846:   int i,ii=0,ip,j; 
                   4847:   double sum; 
                   4848:  
                   4849:   for (i=1;i<=n;i++) { 
                   4850:     ip=indx[i]; 
                   4851:     sum=b[ip]; 
                   4852:     b[ip]=b[i]; 
                   4853:     if (ii) 
                   4854:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4855:     else if (sum) ii=i; 
                   4856:     b[i]=sum; 
                   4857:   } 
                   4858:   for (i=n;i>=1;i--) { 
                   4859:     sum=b[i]; 
                   4860:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4861:     b[i]=sum/a[i][i]; 
                   4862:   } 
                   4863: } 
                   4864: 
                   4865: void pstamp(FILE *fichier)
                   4866: {
1.196     brouard  4867:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4868: }
                   4869: 
1.297     brouard  4870: void date2dmy(double date,double *day, double *month, double *year){
                   4871:   double yp=0., yp1=0., yp2=0.;
                   4872:   
                   4873:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4874:                        fractional in yp1 */
                   4875:   *year=yp;
                   4876:   yp2=modf((yp1*12),&yp);
                   4877:   *month=yp;
                   4878:   yp1=modf((yp2*30.5),&yp);
                   4879:   *day=yp;
                   4880:   if(*day==0) *day=1;
                   4881:   if(*month==0) *month=1;
                   4882: }
                   4883: 
1.253     brouard  4884: 
                   4885: 
1.126     brouard  4886: /************ Frequencies ********************/
1.251     brouard  4887: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4888:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4889:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4890: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  4891:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  4892:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4893:   int iind=0, iage=0;
                   4894:   int mi; /* Effective wave */
                   4895:   int first;
                   4896:   double ***freq; /* Frequencies */
1.268     brouard  4897:   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 */
                   4898:   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  4899:   double *meanq, *stdq, *idq;
1.226     brouard  4900:   double **meanqt;
                   4901:   double *pp, **prop, *posprop, *pospropt;
                   4902:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4903:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4904:   double agebegin, ageend;
                   4905:     
                   4906:   pp=vector(1,nlstate);
1.251     brouard  4907:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4908:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4909:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4910:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4911:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4912:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4913:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4914:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4915:   strcpy(fileresp,"P_");
                   4916:   strcat(fileresp,fileresu);
                   4917:   /*strcat(fileresphtm,fileresu);*/
                   4918:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4919:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4920:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4921:     exit(0);
                   4922:   }
1.240     brouard  4923:   
1.226     brouard  4924:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4925:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4926:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4927:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4928:     fflush(ficlog);
                   4929:     exit(70); 
                   4930:   }
                   4931:   else{
                   4932:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4933: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4934: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4935:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4936:   }
1.319     brouard  4937:   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  4938:   
1.226     brouard  4939:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4940:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4941:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4942:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4943:     fflush(ficlog);
                   4944:     exit(70); 
1.240     brouard  4945:   } else{
1.226     brouard  4946:     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  4947: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4948: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4949:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4950:   }
1.319     brouard  4951:   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  4952:   
1.253     brouard  4953:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4954:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4955:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4956:   j1=0;
1.126     brouard  4957:   
1.227     brouard  4958:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4959:   j=cptcoveff;  /* Only dummy covariates of the model */
1.330     brouard  4960:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  4961:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4962:   
                   4963:   
1.226     brouard  4964:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4965:      reference=low_education V1=0,V2=0
                   4966:      med_educ                V1=1 V2=0, 
                   4967:      high_educ               V1=0 V2=1
1.330     brouard  4968:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  4969:   */
1.249     brouard  4970:   dateintsum=0;
                   4971:   k2cpt=0;
                   4972: 
1.253     brouard  4973:   if(cptcoveff == 0 )
1.265     brouard  4974:     nl=1;  /* Constant and age model only */
1.253     brouard  4975:   else
                   4976:     nl=2;
1.265     brouard  4977: 
                   4978:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4979:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.330     brouard  4980:    *   Loop on j1(1 to 2**cptcovn) covariate combination
1.265     brouard  4981:    *     freq[s1][s2][iage] =0.
                   4982:    *     Loop on iind
                   4983:    *       ++freq[s1][s2][iage] weighted
                   4984:    *     end iind
                   4985:    *     if covariate and j!0
                   4986:    *       headers Variable on one line
                   4987:    *     endif cov j!=0
                   4988:    *     header of frequency table by age
                   4989:    *     Loop on age
                   4990:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4991:    *       pos+=freq[s1][s2][iage] weighted
                   4992:    *       Loop on s1 initial state
                   4993:    *         fprintf(ficresp
                   4994:    *       end s1
                   4995:    *     end age
                   4996:    *     if j!=0 computes starting values
                   4997:    *     end compute starting values
                   4998:    *   end j1
                   4999:    * end nl 
                   5000:    */
1.253     brouard  5001:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5002:     if(nj==1)
                   5003:       j=0;  /* First pass for the constant */
1.265     brouard  5004:     else{
1.330     brouard  5005:       j=cptcovs; /* Other passes for the covariate values */
1.265     brouard  5006:     }
1.251     brouard  5007:     first=1;
1.332     brouard  5008:     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  5009:       posproptt=0.;
1.330     brouard  5010:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5011:        scanf("%d", i);*/
                   5012:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5013:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5014:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5015:            freq[i][s2][m]=0;
1.251     brouard  5016:       
                   5017:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5018:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5019:          prop[i][m]=0;
                   5020:        posprop[i]=0;
                   5021:        pospropt[i]=0;
                   5022:       }
1.283     brouard  5023:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5024:         idq[z1]=0.;
                   5025:         meanq[z1]=0.;
                   5026:         stdq[z1]=0.;
1.283     brouard  5027:       }
                   5028:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5029:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5030:       /*         meanqt[m][z1]=0.; */
                   5031:       /*       } */
                   5032:       /* }       */
1.251     brouard  5033:       /* dateintsum=0; */
                   5034:       /* k2cpt=0; */
                   5035:       
1.265     brouard  5036:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5037:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5038:        bool=1;
                   5039:        if(j !=0){
                   5040:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.330     brouard  5041:            if (cptcovn >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5042:              for (z1=1; z1<=cptcovn; z1++) { /* loops on covariates in the model */
1.251     brouard  5043:                /* if(Tvaraff[z1] ==-20){ */
                   5044:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5045:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5046:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5047:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.332     brouard  5048:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5049:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5050:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5051:                  /* 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", */
                   5052:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5053:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5054:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5055:                } /* Onlyf fixed */
                   5056:              } /* end z1 */
                   5057:            } /* cptcovn > 0 */
                   5058:          } /* end any */
                   5059:        }/* end j==0 */
1.265     brouard  5060:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5061:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5062:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5063:            m=mw[mi][iind];
                   5064:            if(j!=0){
                   5065:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.330     brouard  5066:                for (z1=1; z1<=cptcovn; z1++) {
1.251     brouard  5067:                  if( Fixed[Tmodelind[z1]]==1){
                   5068:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5069:                    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  5070:                                                                                      value is -1, we don't select. It differs from the 
                   5071:                                                                                      constant and age model which counts them. */
                   5072:                      bool=0; /* not selected */
                   5073:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.332     brouard  5074:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.251     brouard  5075:                      bool=0;
                   5076:                    }
                   5077:                  }
                   5078:                }
                   5079:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5080:            } /* end j==0 */
                   5081:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5082:            if(bool==1){ /*Selected */
1.251     brouard  5083:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5084:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5085:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5086:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5087:              if(m >=firstpass && m <=lastpass){
                   5088:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5089:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5090:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5091:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5092:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5093:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5094:                if (m<lastpass) {
                   5095:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5096:                  /*   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]); */
                   5097:                  if(s[m][iind]==-1)
                   5098:                    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.));
                   5099:                  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  5100:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5101:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5102:                      idq[z1]=idq[z1]+weight[iind];
                   5103:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5104:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5105:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5106:                    }
1.284     brouard  5107:                  }
1.251     brouard  5108:                  /* if((int)agev[m][iind] == 55) */
                   5109:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5110:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5111:                  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  5112:                }
1.251     brouard  5113:              } /* end if between passes */  
                   5114:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5115:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5116:                k2cpt++;
                   5117:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5118:              }
1.251     brouard  5119:            }else{
                   5120:              bool=1;
                   5121:            }/* end bool 2 */
                   5122:          } /* end m */
1.284     brouard  5123:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5124:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5125:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5126:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5127:          /* } */
1.251     brouard  5128:        } /* end bool */
                   5129:       } /* end iind = 1 to imx */
1.319     brouard  5130:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5131:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5132:       
                   5133:       
                   5134:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.330     brouard  5135:       if(cptcovn==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5136:         pstamp(ficresp);
1.330     brouard  5137:       if  (cptcovn>0 && j!=0){
1.265     brouard  5138:         pstamp(ficresp);
1.251     brouard  5139:        printf( "\n#********** Variable "); 
                   5140:        fprintf(ficresp, "\n#********** Variable "); 
                   5141:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5142:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5143:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5144:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5145:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5146:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5147:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5148:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5149:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5150:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5151:          }else{
1.330     brouard  5152:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5153:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5154:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5155:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5156:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5157:          }
                   5158:        }
                   5159:        printf( "**********\n#");
                   5160:        fprintf(ficresp, "**********\n#");
                   5161:        fprintf(ficresphtm, "**********</h3>\n");
                   5162:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5163:        fprintf(ficlog, "**********\n");
                   5164:       }
1.284     brouard  5165:       /*
                   5166:        Printing means of quantitative variables if any
                   5167:       */
                   5168:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5169:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5170:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5171:        if(weightopt==1){
                   5172:          printf(" Weighted mean and standard deviation of");
                   5173:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5174:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5175:        }
1.311     brouard  5176:        /* mu = \frac{w x}{\sum w}
                   5177:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5178:        */
                   5179:        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]));
                   5180:        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]));
                   5181:        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  5182:       }
                   5183:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5184:       /*       for(m=1;m<=lastpass;m++){ */
                   5185:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5186:       /*   } */
                   5187:       /* } */
1.283     brouard  5188: 
1.251     brouard  5189:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.330     brouard  5190:       if((cptcovn==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5191:         fprintf(ficresp, " Age");
1.332     brouard  5192:       if(nj==2) for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5193:       for(i=1; i<=nlstate;i++) {
1.330     brouard  5194:        if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5195:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5196:       }
1.330     brouard  5197:       if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5198:       fprintf(ficresphtm, "\n");
                   5199:       
                   5200:       /* Header of frequency table by age */
                   5201:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5202:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5203:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5204:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5205:          if(s2!=0 && m!=0)
                   5206:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5207:        }
1.226     brouard  5208:       }
1.251     brouard  5209:       fprintf(ficresphtmfr, "\n");
                   5210:     
                   5211:       /* For each age */
                   5212:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5213:        fprintf(ficresphtm,"<tr>");
                   5214:        if(iage==iagemax+1){
                   5215:          fprintf(ficlog,"1");
                   5216:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5217:        }else if(iage==iagemax+2){
                   5218:          fprintf(ficlog,"0");
                   5219:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5220:        }else if(iage==iagemax+3){
                   5221:          fprintf(ficlog,"Total");
                   5222:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5223:        }else{
1.240     brouard  5224:          if(first==1){
1.251     brouard  5225:            first=0;
                   5226:            printf("See log file for details...\n");
                   5227:          }
                   5228:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5229:          fprintf(ficlog,"Age %d", iage);
                   5230:        }
1.265     brouard  5231:        for(s1=1; s1 <=nlstate ; s1++){
                   5232:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5233:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5234:        }
1.265     brouard  5235:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5236:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5237:            pos += freq[s1][m][iage];
                   5238:          if(pp[s1]>=1.e-10){
1.251     brouard  5239:            if(first==1){
1.265     brouard  5240:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5241:            }
1.265     brouard  5242:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5243:          }else{
                   5244:            if(first==1)
1.265     brouard  5245:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5246:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5247:          }
                   5248:        }
                   5249:       
1.265     brouard  5250:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5251:          /* posprop[s1]=0; */
                   5252:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5253:            pp[s1] += freq[s1][m][iage];
                   5254:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5255:       
                   5256:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5257:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5258:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5259:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5260:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5261:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5262:        }
                   5263:        
                   5264:        /* Writing ficresp */
1.330     brouard  5265:        if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5266:           if( iage <= iagemax){
                   5267:            fprintf(ficresp," %d",iage);
                   5268:           }
                   5269:         }else if( nj==2){
                   5270:           if( iage <= iagemax){
                   5271:            fprintf(ficresp," %d",iage);
1.332     brouard  5272:             for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5273:           }
1.240     brouard  5274:        }
1.265     brouard  5275:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5276:          if(pos>=1.e-5){
1.251     brouard  5277:            if(first==1)
1.265     brouard  5278:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5279:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5280:          }else{
                   5281:            if(first==1)
1.265     brouard  5282:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5283:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5284:          }
                   5285:          if( iage <= iagemax){
                   5286:            if(pos>=1.e-5){
1.330     brouard  5287:              if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5288:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5289:               }else if( nj==2){
                   5290:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5291:               }
                   5292:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5293:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5294:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5295:            } else{
1.330     brouard  5296:              if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5297:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5298:            }
1.240     brouard  5299:          }
1.265     brouard  5300:          pospropt[s1] +=posprop[s1];
                   5301:        } /* end loop s1 */
1.251     brouard  5302:        /* pospropt=0.; */
1.265     brouard  5303:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5304:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5305:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5306:              if(first==1){
1.265     brouard  5307:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5308:              }
1.265     brouard  5309:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5310:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5311:            }
1.265     brouard  5312:            if(s1!=0 && m!=0)
                   5313:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5314:          }
1.265     brouard  5315:        } /* end loop s1 */
1.251     brouard  5316:        posproptt=0.; 
1.265     brouard  5317:        for(s1=1; s1 <=nlstate; s1++){
                   5318:          posproptt += pospropt[s1];
1.251     brouard  5319:        }
                   5320:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5321:        fprintf(ficresphtm,"</tr>\n");
1.330     brouard  5322:        if((cptcovn==0 && nj==1)|| nj==2 ) {
1.265     brouard  5323:          if(iage <= iagemax)
                   5324:            fprintf(ficresp,"\n");
1.240     brouard  5325:        }
1.251     brouard  5326:        if(first==1)
                   5327:          printf("Others in log...\n");
                   5328:        fprintf(ficlog,"\n");
                   5329:       } /* end loop age iage */
1.265     brouard  5330:       
1.251     brouard  5331:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5332:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5333:        if(posproptt < 1.e-5){
1.265     brouard  5334:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5335:        }else{
1.265     brouard  5336:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5337:        }
1.226     brouard  5338:       }
1.251     brouard  5339:       fprintf(ficresphtm,"</tr>\n");
                   5340:       fprintf(ficresphtm,"</table>\n");
                   5341:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5342:       if(posproptt < 1.e-5){
1.251     brouard  5343:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5344:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5345:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5346:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5347:        invalidvarcomb[j1]=1;
1.226     brouard  5348:       }else{
1.251     brouard  5349:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5350:        invalidvarcomb[j1]=0;
1.226     brouard  5351:       }
1.251     brouard  5352:       fprintf(ficresphtmfr,"</table>\n");
                   5353:       fprintf(ficlog,"\n");
                   5354:       if(j!=0){
                   5355:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5356:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5357:          for(k=1; k <=(nlstate+ndeath); k++){
                   5358:            if (k != i) {
1.265     brouard  5359:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5360:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5361:                  if(j1==1){ /* All dummy covariates to zero */
                   5362:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5363:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5364:                    printf("%d%d ",i,k);
                   5365:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5366:                    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]));
                   5367:                    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]));
                   5368:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5369:                  }
1.253     brouard  5370:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5371:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5372:                    x[iage]= (double)iage;
                   5373:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5374:                    /* 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  5375:                  }
1.268     brouard  5376:                  /* Some are not finite, but linreg will ignore these ages */
                   5377:                  no=0;
1.253     brouard  5378:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5379:                  pstart[s1]=b;
                   5380:                  pstart[s1-1]=a;
1.252     brouard  5381:                }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 */ 
                   5382:                  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]);
                   5383:                  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  5384:                  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  5385:                  printf("%d%d ",i,k);
                   5386:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5387:                  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  5388:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5389:                  ;
                   5390:                }
                   5391:                /* printf("%12.7f )", param[i][jj][k]); */
                   5392:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5393:                s1++; 
1.251     brouard  5394:              } /* end jj */
                   5395:            } /* end k!= i */
                   5396:          } /* end k */
1.265     brouard  5397:        } /* end i, s1 */
1.251     brouard  5398:       } /* end j !=0 */
                   5399:     } /* end selected combination of covariate j1 */
                   5400:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5401:       printf("#Freqsummary: Starting values for the constants:\n");
                   5402:       fprintf(ficlog,"\n");
1.265     brouard  5403:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5404:        for(k=1; k <=(nlstate+ndeath); k++){
                   5405:          if (k != i) {
                   5406:            printf("%d%d ",i,k);
                   5407:            fprintf(ficlog,"%d%d ",i,k);
                   5408:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5409:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5410:              if(jj==1){ /* Age has to be done */
1.265     brouard  5411:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5412:                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]));
                   5413:                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  5414:              }
                   5415:              /* printf("%12.7f )", param[i][jj][k]); */
                   5416:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5417:              s1++; 
1.250     brouard  5418:            }
1.251     brouard  5419:            printf("\n");
                   5420:            fprintf(ficlog,"\n");
1.250     brouard  5421:          }
                   5422:        }
1.284     brouard  5423:       } /* end of state i */
1.251     brouard  5424:       printf("#Freqsummary\n");
                   5425:       fprintf(ficlog,"\n");
1.265     brouard  5426:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5427:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5428:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5429:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5430:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5431:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5432:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5433:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5434:          /* } */
                   5435:        }
1.265     brouard  5436:       } /* end loop s1 */
1.251     brouard  5437:       
                   5438:       printf("\n");
                   5439:       fprintf(ficlog,"\n");
                   5440:     } /* end j=0 */
1.249     brouard  5441:   } /* end j */
1.252     brouard  5442: 
1.253     brouard  5443:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5444:     for(i=1, jk=1; i <=nlstate; i++){
                   5445:       for(j=1; j <=nlstate+ndeath; j++){
                   5446:        if(j!=i){
                   5447:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5448:          printf("%1d%1d",i,j);
                   5449:          fprintf(ficparo,"%1d%1d",i,j);
                   5450:          for(k=1; k<=ncovmodel;k++){
                   5451:            /*    printf(" %lf",param[i][j][k]); */
                   5452:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5453:            p[jk]=pstart[jk];
                   5454:            printf(" %f ",pstart[jk]);
                   5455:            fprintf(ficparo," %f ",pstart[jk]);
                   5456:            jk++;
                   5457:          }
                   5458:          printf("\n");
                   5459:          fprintf(ficparo,"\n");
                   5460:        }
                   5461:       }
                   5462:     }
                   5463:   } /* end mle=-2 */
1.226     brouard  5464:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5465:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5466:   
1.226     brouard  5467:   fclose(ficresp);
                   5468:   fclose(ficresphtm);
                   5469:   fclose(ficresphtmfr);
1.283     brouard  5470:   free_vector(idq,1,nqfveff);
1.226     brouard  5471:   free_vector(meanq,1,nqfveff);
1.284     brouard  5472:   free_vector(stdq,1,nqfveff);
1.226     brouard  5473:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5474:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5475:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5476:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5477:   free_vector(pospropt,1,nlstate);
                   5478:   free_vector(posprop,1,nlstate);
1.251     brouard  5479:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5480:   free_vector(pp,1,nlstate);
                   5481:   /* End of freqsummary */
                   5482: }
1.126     brouard  5483: 
1.268     brouard  5484: /* Simple linear regression */
                   5485: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5486: 
                   5487:   /* y=a+bx regression */
                   5488:   double   sumx = 0.0;                        /* sum of x                      */
                   5489:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5490:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5491:   double   sumy = 0.0;                        /* sum of y                      */
                   5492:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5493:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5494:   double yhat;
                   5495:   
                   5496:   double denom=0;
                   5497:   int i;
                   5498:   int ne=*no;
                   5499:   
                   5500:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5501:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5502:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5503:       continue;
                   5504:     }
                   5505:     ne=ne+1;
                   5506:     sumx  += x[i];       
                   5507:     sumx2 += x[i]*x[i];  
                   5508:     sumxy += x[i] * y[i];
                   5509:     sumy  += y[i];      
                   5510:     sumy2 += y[i]*y[i]; 
                   5511:     denom = (ne * sumx2 - sumx*sumx);
                   5512:     /* 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); */
                   5513:   } 
                   5514:   
                   5515:   denom = (ne * sumx2 - sumx*sumx);
                   5516:   if (denom == 0) {
                   5517:     // vertical, slope m is infinity
                   5518:     *b = INFINITY;
                   5519:     *a = 0;
                   5520:     if (r) *r = 0;
                   5521:     return 1;
                   5522:   }
                   5523:   
                   5524:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5525:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5526:   if (r!=NULL) {
                   5527:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5528:       sqrt((sumx2 - sumx*sumx/ne) *
                   5529:           (sumy2 - sumy*sumy/ne));
                   5530:   }
                   5531:   *no=ne;
                   5532:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5533:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5534:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5535:       continue;
                   5536:     }
                   5537:     ne=ne+1;
                   5538:     yhat = y[i] - *a -*b* x[i];
                   5539:     sume2  += yhat * yhat ;       
                   5540:     
                   5541:     denom = (ne * sumx2 - sumx*sumx);
                   5542:     /* 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); */
                   5543:   } 
                   5544:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5545:   *sa= *sb * sqrt(sumx2/ne);
                   5546:   
                   5547:   return 0; 
                   5548: }
                   5549: 
1.126     brouard  5550: /************ Prevalence ********************/
1.227     brouard  5551: 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)
                   5552: {  
                   5553:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5554:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5555:      We still use firstpass and lastpass as another selection.
                   5556:   */
1.126     brouard  5557:  
1.227     brouard  5558:   int i, m, jk, j1, bool, z1,j, iv;
                   5559:   int mi; /* Effective wave */
                   5560:   int iage;
                   5561:   double agebegin, ageend;
                   5562: 
                   5563:   double **prop;
                   5564:   double posprop; 
                   5565:   double  y2; /* in fractional years */
                   5566:   int iagemin, iagemax;
                   5567:   int first; /** to stop verbosity which is redirected to log file */
                   5568: 
                   5569:   iagemin= (int) agemin;
                   5570:   iagemax= (int) agemax;
                   5571:   /*pp=vector(1,nlstate);*/
1.251     brouard  5572:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5573:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5574:   j1=0;
1.222     brouard  5575:   
1.227     brouard  5576:   /*j=cptcoveff;*/
                   5577:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5578:   
1.288     brouard  5579:   first=0;
1.227     brouard  5580:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5581:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5582:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5583:        prop[i][iage]=0.0;
                   5584:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5585:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5586:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5587:     
                   5588:     for (i=1; i<=imx; i++) { /* Each individual */
                   5589:       bool=1;
                   5590:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5591:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5592:        m=mw[mi][i];
                   5593:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5594:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5595:        for (z1=1; z1<=cptcoveff; z1++){
                   5596:          if( Fixed[Tmodelind[z1]]==1){
                   5597:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5598:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5599:              bool=0;
                   5600:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5601:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5602:              bool=0;
                   5603:            }
                   5604:        }
                   5605:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5606:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5607:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5608:          if(m >=firstpass && m <=lastpass){
                   5609:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5610:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5611:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5612:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5613:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5614:                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); 
                   5615:                exit(1);
                   5616:              }
                   5617:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5618:                /*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]]);*/
                   5619:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5620:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5621:              } /* end valid statuses */ 
                   5622:            } /* end selection of dates */
                   5623:          } /* end selection of waves */
                   5624:        } /* end bool */
                   5625:       } /* end wave */
                   5626:     } /* end individual */
                   5627:     for(i=iagemin; i <= iagemax+3; i++){  
                   5628:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5629:        posprop += prop[jk][i]; 
                   5630:       } 
                   5631:       
                   5632:       for(jk=1; jk <=nlstate ; jk++){      
                   5633:        if( i <=  iagemax){ 
                   5634:          if(posprop>=1.e-5){ 
                   5635:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5636:          } else{
1.288     brouard  5637:            if(!first){
                   5638:              first=1;
1.266     brouard  5639:              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]);
                   5640:            }else{
1.288     brouard  5641:              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  5642:            }
                   5643:          }
                   5644:        } 
                   5645:       }/* end jk */ 
                   5646:     }/* end i */ 
1.222     brouard  5647:      /*} *//* end i1 */
1.227     brouard  5648:   } /* end j1 */
1.222     brouard  5649:   
1.227     brouard  5650:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5651:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5652:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5653: }  /* End of prevalence */
1.126     brouard  5654: 
                   5655: /************* Waves Concatenation ***************/
                   5656: 
                   5657: 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)
                   5658: {
1.298     brouard  5659:   /* 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  5660:      Death is a valid wave (if date is known).
                   5661:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5662:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5663:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5664:   */
1.126     brouard  5665: 
1.224     brouard  5666:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5667:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5668:      double sum=0., jmean=0.;*/
1.224     brouard  5669:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5670:   int j, k=0,jk, ju, jl;
                   5671:   double sum=0.;
                   5672:   first=0;
1.214     brouard  5673:   firstwo=0;
1.217     brouard  5674:   firsthree=0;
1.218     brouard  5675:   firstfour=0;
1.164     brouard  5676:   jmin=100000;
1.126     brouard  5677:   jmax=-1;
                   5678:   jmean=0.;
1.224     brouard  5679: 
                   5680: /* Treating live states */
1.214     brouard  5681:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5682:     mi=0;  /* First valid wave */
1.227     brouard  5683:     mli=0; /* Last valid wave */
1.309     brouard  5684:     m=firstpass;  /* Loop on waves */
                   5685:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5686:       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 */
                   5687:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5688:       }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  5689:        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  5690:        mli=m;
1.224     brouard  5691:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5692:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5693:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5694:       }
1.309     brouard  5695:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5696: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5697:        break;
1.224     brouard  5698: #else
1.317     brouard  5699:        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  5700:          if(firsthree == 0){
1.302     brouard  5701:            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  5702:            firsthree=1;
1.317     brouard  5703:          }else if(firsthree >=1 && firsthree < 10){
                   5704:            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);
                   5705:            firsthree++;
                   5706:          }else if(firsthree == 10){
                   5707:            printf("Information, too many Information flags: no more reported to log either\n");
                   5708:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5709:            firsthree++;
                   5710:          }else{
                   5711:            firsthree++;
1.227     brouard  5712:          }
1.309     brouard  5713:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5714:          mli=m;
                   5715:        }
                   5716:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5717:          nbwarn++;
1.309     brouard  5718:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5719:            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);
                   5720:            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);
                   5721:          }
                   5722:          break;
                   5723:        }
                   5724:        break;
1.224     brouard  5725: #endif
1.227     brouard  5726:       }/* End m >= lastpass */
1.126     brouard  5727:     }/* end while */
1.224     brouard  5728: 
1.227     brouard  5729:     /* 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  5730:     /* After last pass */
1.224     brouard  5731: /* Treating death states */
1.214     brouard  5732:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5733:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5734:       /* } */
1.126     brouard  5735:       mi++;    /* Death is another wave */
                   5736:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5737:       /* Only death is a correct wave */
1.126     brouard  5738:       mw[mi][i]=m;
1.257     brouard  5739:     } /* else not in a death state */
1.224     brouard  5740: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5741:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5742:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5743:        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  5744:          nbwarn++;
                   5745:          if(firstfiv==0){
1.309     brouard  5746:            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  5747:            firstfiv=1;
                   5748:          }else{
1.309     brouard  5749:            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  5750:          }
1.309     brouard  5751:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5752:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5753:          nberr++;
                   5754:          if(firstwo==0){
1.309     brouard  5755:            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  5756:            firstwo=1;
                   5757:          }
1.309     brouard  5758:          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  5759:        }
1.257     brouard  5760:       }else{ /* if date of interview is unknown */
1.227     brouard  5761:        /* death is known but not confirmed by death status at any wave */
                   5762:        if(firstfour==0){
1.309     brouard  5763:          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  5764:          firstfour=1;
                   5765:        }
1.309     brouard  5766:        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  5767:       }
1.224     brouard  5768:     } /* end if date of death is known */
                   5769: #endif
1.309     brouard  5770:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5771:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5772:     if(mi==0){
                   5773:       nbwarn++;
                   5774:       if(first==0){
1.227     brouard  5775:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5776:        first=1;
1.126     brouard  5777:       }
                   5778:       if(first==1){
1.227     brouard  5779:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5780:       }
                   5781:     } /* end mi==0 */
                   5782:   } /* End individuals */
1.214     brouard  5783:   /* wav and mw are no more changed */
1.223     brouard  5784:        
1.317     brouard  5785:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5786:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5787: 
                   5788: 
1.126     brouard  5789:   for(i=1; i<=imx; i++){
                   5790:     for(mi=1; mi<wav[i];mi++){
                   5791:       if (stepm <=0)
1.227     brouard  5792:        dh[mi][i]=1;
1.126     brouard  5793:       else{
1.260     brouard  5794:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5795:          if (agedc[i] < 2*AGESUP) {
                   5796:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5797:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5798:            else if(j<0){
                   5799:              nberr++;
                   5800:              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]);
                   5801:              j=1; /* Temporary Dangerous patch */
                   5802:              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);
                   5803:              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]);
                   5804:              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);
                   5805:            }
                   5806:            k=k+1;
                   5807:            if (j >= jmax){
                   5808:              jmax=j;
                   5809:              ijmax=i;
                   5810:            }
                   5811:            if (j <= jmin){
                   5812:              jmin=j;
                   5813:              ijmin=i;
                   5814:            }
                   5815:            sum=sum+j;
                   5816:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5817:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5818:          }
                   5819:        }
                   5820:        else{
                   5821:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5822: /*       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  5823:                                        
1.227     brouard  5824:          k=k+1;
                   5825:          if (j >= jmax) {
                   5826:            jmax=j;
                   5827:            ijmax=i;
                   5828:          }
                   5829:          else if (j <= jmin){
                   5830:            jmin=j;
                   5831:            ijmin=i;
                   5832:          }
                   5833:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5834:          /*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]);*/
                   5835:          if(j<0){
                   5836:            nberr++;
                   5837:            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]);
                   5838:            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]);
                   5839:          }
                   5840:          sum=sum+j;
                   5841:        }
                   5842:        jk= j/stepm;
                   5843:        jl= j -jk*stepm;
                   5844:        ju= j -(jk+1)*stepm;
                   5845:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5846:          if(jl==0){
                   5847:            dh[mi][i]=jk;
                   5848:            bh[mi][i]=0;
                   5849:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5850:                  * to avoid the price of an extra matrix product in likelihood */
                   5851:            dh[mi][i]=jk+1;
                   5852:            bh[mi][i]=ju;
                   5853:          }
                   5854:        }else{
                   5855:          if(jl <= -ju){
                   5856:            dh[mi][i]=jk;
                   5857:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5858:                                 * is higher than the multiple of stepm and negative otherwise.
                   5859:                                 */
                   5860:          }
                   5861:          else{
                   5862:            dh[mi][i]=jk+1;
                   5863:            bh[mi][i]=ju;
                   5864:          }
                   5865:          if(dh[mi][i]==0){
                   5866:            dh[mi][i]=1; /* At least one step */
                   5867:            bh[mi][i]=ju; /* At least one step */
                   5868:            /*  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);*/
                   5869:          }
                   5870:        } /* end if mle */
1.126     brouard  5871:       }
                   5872:     } /* end wave */
                   5873:   }
                   5874:   jmean=sum/k;
                   5875:   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  5876:   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  5877: }
1.126     brouard  5878: 
                   5879: /*********** Tricode ****************************/
1.220     brouard  5880:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5881:  {
                   5882:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5883:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5884:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5885:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5886:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5887:     */
1.130     brouard  5888: 
1.242     brouard  5889:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5890:    int modmaxcovj=0; /* Modality max of covariates j */
                   5891:    int cptcode=0; /* Modality max of covariates j */
                   5892:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5893: 
                   5894: 
1.242     brouard  5895:    /* cptcoveff=0;  */
                   5896:    /* *cptcov=0; */
1.126     brouard  5897:  
1.242     brouard  5898:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5899:    for (k=1; k <= maxncov; k++)
                   5900:      for(j=1; j<=2; j++)
                   5901:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5902: 
1.242     brouard  5903:    /* Loop on covariates without age and products and no quantitative variable */
                   5904:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5905:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5906:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5907:        switch(Fixed[k]) {
                   5908:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5909:         modmaxcovj=0;
                   5910:         modmincovj=0;
1.242     brouard  5911:         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*/
                   5912:           ij=(int)(covar[Tvar[k]][i]);
                   5913:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5914:            * If product of Vn*Vm, still boolean *:
                   5915:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5916:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5917:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5918:              modality of the nth covariate of individual i. */
                   5919:           if (ij > modmaxcovj)
                   5920:             modmaxcovj=ij; 
                   5921:           else if (ij < modmincovj) 
                   5922:             modmincovj=ij; 
1.287     brouard  5923:           if (ij <0 || ij >1 ){
1.311     brouard  5924:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5925:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5926:             fflush(ficlog);
                   5927:             exit(1);
1.287     brouard  5928:           }
                   5929:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5930:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5931:             exit(1);
                   5932:           }else
                   5933:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5934:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5935:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5936:           /* getting the maximum value of the modality of the covariate
                   5937:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5938:              female ies 1, then modmaxcovj=1.
                   5939:           */
                   5940:         } /* end for loop on individuals i */
                   5941:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5942:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5943:         cptcode=modmaxcovj;
                   5944:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5945:         /*for (i=0; i<=cptcode; i++) {*/
                   5946:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5947:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5948:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5949:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5950:             if( j != -1){
                   5951:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5952:                                  covariate for which somebody answered excluding 
                   5953:                                  undefined. Usually 2: 0 and 1. */
                   5954:             }
                   5955:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5956:                                     covariate for which somebody answered including 
                   5957:                                     undefined. Usually 3: -1, 0 and 1. */
                   5958:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5959:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5960:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5961:                        
1.242     brouard  5962:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5963:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5964:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5965:         /* modmincovj=3; modmaxcovj = 7; */
                   5966:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5967:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5968:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5969:         /* nbcode[Tvar[j]][ij]=k; */
                   5970:         /* nbcode[Tvar[j]][1]=0; */
                   5971:         /* nbcode[Tvar[j]][2]=1; */
                   5972:         /* nbcode[Tvar[j]][3]=2; */
                   5973:         /* To be continued (not working yet). */
                   5974:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5975: 
                   5976:         /* 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*/
                   5977:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5978:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5979:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5980:         /*, could be restored in the future */
                   5981:         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  5982:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5983:             break;
                   5984:           }
                   5985:           ij++;
1.287     brouard  5986:           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  5987:           cptcode = ij; /* New max modality for covar j */
                   5988:         } /* end of loop on modality i=-1 to 1 or more */
                   5989:         break;
                   5990:        case 1: /* Testing on varying covariate, could be simple and
                   5991:                * should look at waves or product of fixed *
                   5992:                * varying. No time to test -1, assuming 0 and 1 only */
                   5993:         ij=0;
                   5994:         for(i=0; i<=1;i++){
                   5995:           nbcode[Tvar[k]][++ij]=i;
                   5996:         }
                   5997:         break;
                   5998:        default:
                   5999:         break;
                   6000:        } /* end switch */
                   6001:      } /* end dummy test */
1.311     brouard  6002:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   6003:        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*/
                   6004:         if(isnan(covar[Tvar[k]][i])){
                   6005:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6006:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6007:           fflush(ficlog);
                   6008:           exit(1);
                   6009:          }
                   6010:        }
                   6011:      }
1.287     brouard  6012:    } /* 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  6013:   
                   6014:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6015:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6016:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6017:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6018:      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 */ 
                   6019:      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 */
                   6020:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6021:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6022:   
                   6023:    ij=0;
                   6024:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   6025:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   6026:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6027:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   6028:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   6029:        /* If product not in single variable we don't print results */
                   6030:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6031:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   6032:        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*/
                   6033:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6034:        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 */
                   6035:        if(Fixed[k]!=0)
                   6036:         anyvaryingduminmodel=1;
                   6037:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6038:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6039:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6040:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6041:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6042:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6043:      } 
                   6044:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6045:    /* ij--; */
                   6046:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.330     brouard  6047:    *cptcov=ij; /* cptcov= Number of total real effective covariates: effective (used as cptcoveff in other functions)
1.242     brouard  6048:                * because they can be excluded from the model and real
                   6049:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6050:    for(j=ij+1; j<= cptcovt; j++){
                   6051:      Tvaraff[j]=0;
                   6052:      Tmodelind[j]=0;
                   6053:    }
                   6054:    for(j=ntveff+1; j<= cptcovt; j++){
                   6055:      TmodelInvind[j]=0;
                   6056:    }
                   6057:    /* To be sorted */
                   6058:    ;
                   6059:  }
1.126     brouard  6060: 
1.145     brouard  6061: 
1.126     brouard  6062: /*********** Health Expectancies ****************/
                   6063: 
1.235     brouard  6064:  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  6065: 
                   6066: {
                   6067:   /* Health expectancies, no variances */
1.329     brouard  6068:   /* cij is the combination in the list of combination of dummy covariates */
                   6069:   /* strstart is a string of time at start of computing */
1.164     brouard  6070:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6071:   int nhstepma, nstepma; /* Decreasing with age */
                   6072:   double age, agelim, hf;
                   6073:   double ***p3mat;
                   6074:   double eip;
                   6075: 
1.238     brouard  6076:   /* pstamp(ficreseij); */
1.126     brouard  6077:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6078:   fprintf(ficreseij,"# Age");
                   6079:   for(i=1; i<=nlstate;i++){
                   6080:     for(j=1; j<=nlstate;j++){
                   6081:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6082:     }
                   6083:     fprintf(ficreseij," e%1d. ",i);
                   6084:   }
                   6085:   fprintf(ficreseij,"\n");
                   6086: 
                   6087:   
                   6088:   if(estepm < stepm){
                   6089:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6090:   }
                   6091:   else  hstepm=estepm;   
                   6092:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6093:    * This is mainly to measure the difference between two models: for example
                   6094:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6095:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6096:    * progression in between and thus overestimating or underestimating according
                   6097:    * to the curvature of the survival function. If, for the same date, we 
                   6098:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6099:    * to compare the new estimate of Life expectancy with the same linear 
                   6100:    * hypothesis. A more precise result, taking into account a more precise
                   6101:    * curvature will be obtained if estepm is as small as stepm. */
                   6102: 
                   6103:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6104:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6105:      nhstepm is the number of hstepm from age to agelim 
                   6106:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6107:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6108:      and note for a fixed period like estepm months */
                   6109:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6110:      survival function given by stepm (the optimization length). Unfortunately it
                   6111:      means that if the survival funtion is printed only each two years of age and if
                   6112:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6113:      results. So we changed our mind and took the option of the best precision.
                   6114:   */
                   6115:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6116: 
                   6117:   agelim=AGESUP;
                   6118:   /* If stepm=6 months */
                   6119:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6120:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6121:     
                   6122: /* nhstepm age range expressed in number of stepm */
                   6123:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6124:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6125:   /* if (stepm >= YEARM) hstepm=1;*/
                   6126:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6127:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6128: 
                   6129:   for (age=bage; age<=fage; age ++){ 
                   6130:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6131:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6132:     /* if (stepm >= YEARM) hstepm=1;*/
                   6133:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6134: 
                   6135:     /* If stepm=6 months */
                   6136:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6137:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6138:     /* 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  6139:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6140:     
                   6141:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6142:     
                   6143:     printf("%d|",(int)age);fflush(stdout);
                   6144:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6145:     
                   6146:     /* Computing expectancies */
                   6147:     for(i=1; i<=nlstate;i++)
                   6148:       for(j=1; j<=nlstate;j++)
                   6149:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6150:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6151:          
                   6152:          /* 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]);*/
                   6153: 
                   6154:        }
                   6155: 
                   6156:     fprintf(ficreseij,"%3.0f",age );
                   6157:     for(i=1; i<=nlstate;i++){
                   6158:       eip=0;
                   6159:       for(j=1; j<=nlstate;j++){
                   6160:        eip +=eij[i][j][(int)age];
                   6161:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6162:       }
                   6163:       fprintf(ficreseij,"%9.4f", eip );
                   6164:     }
                   6165:     fprintf(ficreseij,"\n");
                   6166:     
                   6167:   }
                   6168:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6169:   printf("\n");
                   6170:   fprintf(ficlog,"\n");
                   6171:   
                   6172: }
                   6173: 
1.235     brouard  6174:  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  6175: 
                   6176: {
                   6177:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6178:      to initial status i, ei. .
1.126     brouard  6179:   */
                   6180:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6181:   int nhstepma, nstepma; /* Decreasing with age */
                   6182:   double age, agelim, hf;
                   6183:   double ***p3matp, ***p3matm, ***varhe;
                   6184:   double **dnewm,**doldm;
                   6185:   double *xp, *xm;
                   6186:   double **gp, **gm;
                   6187:   double ***gradg, ***trgradg;
                   6188:   int theta;
                   6189: 
                   6190:   double eip, vip;
                   6191: 
                   6192:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6193:   xp=vector(1,npar);
                   6194:   xm=vector(1,npar);
                   6195:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6196:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6197:   
                   6198:   pstamp(ficresstdeij);
                   6199:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6200:   fprintf(ficresstdeij,"# Age");
                   6201:   for(i=1; i<=nlstate;i++){
                   6202:     for(j=1; j<=nlstate;j++)
                   6203:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6204:     fprintf(ficresstdeij," e%1d. ",i);
                   6205:   }
                   6206:   fprintf(ficresstdeij,"\n");
                   6207: 
                   6208:   pstamp(ficrescveij);
                   6209:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6210:   fprintf(ficrescveij,"# Age");
                   6211:   for(i=1; i<=nlstate;i++)
                   6212:     for(j=1; j<=nlstate;j++){
                   6213:       cptj= (j-1)*nlstate+i;
                   6214:       for(i2=1; i2<=nlstate;i2++)
                   6215:        for(j2=1; j2<=nlstate;j2++){
                   6216:          cptj2= (j2-1)*nlstate+i2;
                   6217:          if(cptj2 <= cptj)
                   6218:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6219:        }
                   6220:     }
                   6221:   fprintf(ficrescveij,"\n");
                   6222:   
                   6223:   if(estepm < stepm){
                   6224:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6225:   }
                   6226:   else  hstepm=estepm;   
                   6227:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6228:    * This is mainly to measure the difference between two models: for example
                   6229:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6230:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6231:    * progression in between and thus overestimating or underestimating according
                   6232:    * to the curvature of the survival function. If, for the same date, we 
                   6233:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6234:    * to compare the new estimate of Life expectancy with the same linear 
                   6235:    * hypothesis. A more precise result, taking into account a more precise
                   6236:    * curvature will be obtained if estepm is as small as stepm. */
                   6237: 
                   6238:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6239:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6240:      nhstepm is the number of hstepm from age to agelim 
                   6241:      nstepm is the number of stepm from age to agelin. 
                   6242:      Look at hpijx to understand the reason of that which relies in memory size
                   6243:      and note for a fixed period like estepm months */
                   6244:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6245:      survival function given by stepm (the optimization length). Unfortunately it
                   6246:      means that if the survival funtion is printed only each two years of age and if
                   6247:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6248:      results. So we changed our mind and took the option of the best precision.
                   6249:   */
                   6250:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6251: 
                   6252:   /* If stepm=6 months */
                   6253:   /* nhstepm age range expressed in number of stepm */
                   6254:   agelim=AGESUP;
                   6255:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6256:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6257:   /* if (stepm >= YEARM) hstepm=1;*/
                   6258:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6259:   
                   6260:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6261:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6262:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6263:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6264:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6265:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6266: 
                   6267:   for (age=bage; age<=fage; age ++){ 
                   6268:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6269:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6270:     /* if (stepm >= YEARM) hstepm=1;*/
                   6271:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6272:                
1.126     brouard  6273:     /* If stepm=6 months */
                   6274:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6275:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6276:     
                   6277:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6278:                
1.126     brouard  6279:     /* Computing  Variances of health expectancies */
                   6280:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6281:        decrease memory allocation */
                   6282:     for(theta=1; theta <=npar; theta++){
                   6283:       for(i=1; i<=npar; i++){ 
1.222     brouard  6284:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6285:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6286:       }
1.235     brouard  6287:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6288:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6289:                        
1.126     brouard  6290:       for(j=1; j<= nlstate; j++){
1.222     brouard  6291:        for(i=1; i<=nlstate; i++){
                   6292:          for(h=0; h<=nhstepm-1; h++){
                   6293:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6294:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6295:          }
                   6296:        }
1.126     brouard  6297:       }
1.218     brouard  6298:                        
1.126     brouard  6299:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6300:        for(h=0; h<=nhstepm-1; h++){
                   6301:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6302:        }
1.126     brouard  6303:     }/* End theta */
                   6304:     
                   6305:     
                   6306:     for(h=0; h<=nhstepm-1; h++)
                   6307:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6308:        for(theta=1; theta <=npar; theta++)
                   6309:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6310:     
1.218     brouard  6311:                
1.222     brouard  6312:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6313:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6314:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6315:                
1.222     brouard  6316:     printf("%d|",(int)age);fflush(stdout);
                   6317:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6318:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6319:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6320:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6321:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6322:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6323:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6324:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6325:       }
                   6326:     }
1.320     brouard  6327:     /* if((int)age ==50){ */
                   6328:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6329:     /* } */
1.126     brouard  6330:     /* Computing expectancies */
1.235     brouard  6331:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6332:     for(i=1; i<=nlstate;i++)
                   6333:       for(j=1; j<=nlstate;j++)
1.222     brouard  6334:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6335:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6336:                                        
1.222     brouard  6337:          /* 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  6338:                                        
1.222     brouard  6339:        }
1.269     brouard  6340: 
                   6341:     /* Standard deviation of expectancies ij */                
1.126     brouard  6342:     fprintf(ficresstdeij,"%3.0f",age );
                   6343:     for(i=1; i<=nlstate;i++){
                   6344:       eip=0.;
                   6345:       vip=0.;
                   6346:       for(j=1; j<=nlstate;j++){
1.222     brouard  6347:        eip += eij[i][j][(int)age];
                   6348:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6349:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6350:        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  6351:       }
                   6352:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6353:     }
                   6354:     fprintf(ficresstdeij,"\n");
1.218     brouard  6355:                
1.269     brouard  6356:     /* Variance of expectancies ij */          
1.126     brouard  6357:     fprintf(ficrescveij,"%3.0f",age );
                   6358:     for(i=1; i<=nlstate;i++)
                   6359:       for(j=1; j<=nlstate;j++){
1.222     brouard  6360:        cptj= (j-1)*nlstate+i;
                   6361:        for(i2=1; i2<=nlstate;i2++)
                   6362:          for(j2=1; j2<=nlstate;j2++){
                   6363:            cptj2= (j2-1)*nlstate+i2;
                   6364:            if(cptj2 <= cptj)
                   6365:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6366:          }
1.126     brouard  6367:       }
                   6368:     fprintf(ficrescveij,"\n");
1.218     brouard  6369:                
1.126     brouard  6370:   }
                   6371:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6372:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6373:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6374:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6375:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6376:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6377:   printf("\n");
                   6378:   fprintf(ficlog,"\n");
1.218     brouard  6379:        
1.126     brouard  6380:   free_vector(xm,1,npar);
                   6381:   free_vector(xp,1,npar);
                   6382:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6383:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6384:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6385: }
1.218     brouard  6386:  
1.126     brouard  6387: /************ Variance ******************/
1.235     brouard  6388:  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  6389:  {
1.279     brouard  6390:    /** Variance of health expectancies 
                   6391:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6392:     * double **newm;
                   6393:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6394:     */
1.218     brouard  6395:   
                   6396:    /* int movingaverage(); */
                   6397:    double **dnewm,**doldm;
                   6398:    double **dnewmp,**doldmp;
                   6399:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6400:    int first=0;
1.218     brouard  6401:    int k;
                   6402:    double *xp;
1.279     brouard  6403:    double **gp, **gm;  /**< for var eij */
                   6404:    double ***gradg, ***trgradg; /**< for var eij */
                   6405:    double **gradgp, **trgradgp; /**< for var p point j */
                   6406:    double *gpp, *gmp; /**< for var p point j */
                   6407:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6408:    double ***p3mat;
                   6409:    double age,agelim, hf;
                   6410:    /* double ***mobaverage; */
                   6411:    int theta;
                   6412:    char digit[4];
                   6413:    char digitp[25];
                   6414: 
                   6415:    char fileresprobmorprev[FILENAMELENGTH];
                   6416: 
                   6417:    if(popbased==1){
                   6418:      if(mobilav!=0)
                   6419:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6420:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6421:    }
                   6422:    else 
                   6423:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6424: 
1.218     brouard  6425:    /* if (mobilav!=0) { */
                   6426:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6427:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6428:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6429:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6430:    /*   } */
                   6431:    /* } */
                   6432: 
                   6433:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6434:    sprintf(digit,"%-d",ij);
                   6435:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6436:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6437:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6438:    strcat(fileresprobmorprev,fileresu);
                   6439:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6440:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6441:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6442:    }
                   6443:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6444:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6445:    pstamp(ficresprobmorprev);
                   6446:    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  6447:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6448:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  6449:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  6450:    }
                   6451:    for(j=1;j<=cptcoveff;j++) 
1.332     brouard  6452:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]);
1.238     brouard  6453:    fprintf(ficresprobmorprev,"\n");
                   6454: 
1.218     brouard  6455:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6456:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6457:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6458:      for(i=1; i<=nlstate;i++)
                   6459:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6460:    }  
                   6461:    fprintf(ficresprobmorprev,"\n");
                   6462:   
                   6463:    fprintf(ficgp,"\n# Routine varevsij");
                   6464:    fprintf(ficgp,"\nunset title \n");
                   6465:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6466:    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");
                   6467:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6468: 
1.218     brouard  6469:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6470:    pstamp(ficresvij);
                   6471:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6472:    if(popbased==1)
                   6473:      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);
                   6474:    else
                   6475:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6476:    fprintf(ficresvij,"# Age");
                   6477:    for(i=1; i<=nlstate;i++)
                   6478:      for(j=1; j<=nlstate;j++)
                   6479:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6480:    fprintf(ficresvij,"\n");
                   6481: 
                   6482:    xp=vector(1,npar);
                   6483:    dnewm=matrix(1,nlstate,1,npar);
                   6484:    doldm=matrix(1,nlstate,1,nlstate);
                   6485:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6486:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6487: 
                   6488:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6489:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6490:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6491:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6492:   
1.218     brouard  6493:    if(estepm < stepm){
                   6494:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6495:    }
                   6496:    else  hstepm=estepm;   
                   6497:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6498:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6499:       nhstepm is the number of hstepm from age to agelim 
                   6500:       nstepm is the number of stepm from age to agelim. 
                   6501:       Look at function hpijx to understand why because of memory size limitations, 
                   6502:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6503:       survival function given by stepm (the optimization length). Unfortunately it
                   6504:       means that if the survival funtion is printed every two years of age and if
                   6505:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6506:       results. So we changed our mind and took the option of the best precision.
                   6507:    */
                   6508:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6509:    agelim = AGESUP;
                   6510:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6511:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6512:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6513:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6514:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6515:      gp=matrix(0,nhstepm,1,nlstate);
                   6516:      gm=matrix(0,nhstepm,1,nlstate);
                   6517:                
                   6518:                
                   6519:      for(theta=1; theta <=npar; theta++){
                   6520:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6521:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6522:        }
1.279     brouard  6523:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6524:        * returns into prlim .
1.288     brouard  6525:        */
1.242     brouard  6526:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6527: 
                   6528:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6529:        if (popbased==1) {
                   6530:         if(mobilav ==0){
                   6531:           for(i=1; i<=nlstate;i++)
                   6532:             prlim[i][i]=probs[(int)age][i][ij];
                   6533:         }else{ /* mobilav */ 
                   6534:           for(i=1; i<=nlstate;i++)
                   6535:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6536:         }
                   6537:        }
1.295     brouard  6538:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6539:        */                      
                   6540:        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  6541:        /**< 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  6542:        * at horizon h in state j including mortality.
                   6543:        */
1.218     brouard  6544:        for(j=1; j<= nlstate; j++){
                   6545:         for(h=0; h<=nhstepm; h++){
                   6546:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6547:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6548:         }
                   6549:        }
1.279     brouard  6550:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6551:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6552:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6553:        */
                   6554:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6555:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6556:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6557:        }
                   6558:        
                   6559:        /* Again with minus shift */
1.218     brouard  6560:                        
                   6561:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6562:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6563: 
1.242     brouard  6564:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6565:                        
                   6566:        if (popbased==1) {
                   6567:         if(mobilav ==0){
                   6568:           for(i=1; i<=nlstate;i++)
                   6569:             prlim[i][i]=probs[(int)age][i][ij];
                   6570:         }else{ /* mobilav */ 
                   6571:           for(i=1; i<=nlstate;i++)
                   6572:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6573:         }
                   6574:        }
                   6575:                        
1.235     brouard  6576:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6577:                        
                   6578:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6579:         for(h=0; h<=nhstepm; h++){
                   6580:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6581:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6582:         }
                   6583:        }
                   6584:        /* This for computing probability of death (h=1 means
                   6585:          computed over hstepm matrices product = hstepm*stepm months) 
                   6586:          as a weighted average of prlim.
                   6587:        */
                   6588:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6589:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6590:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6591:        }    
1.279     brouard  6592:        /* end shifting computations */
                   6593: 
                   6594:        /**< Computing gradient matrix at horizon h 
                   6595:        */
1.218     brouard  6596:        for(j=1; j<= nlstate; j++) /* vareij */
                   6597:         for(h=0; h<=nhstepm; h++){
                   6598:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6599:         }
1.279     brouard  6600:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6601:        */
                   6602:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6603:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6604:        }
                   6605:                        
                   6606:      } /* End theta */
1.279     brouard  6607:      
                   6608:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6609:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6610:                
                   6611:      for(h=0; h<=nhstepm; h++) /* veij */
                   6612:        for(j=1; j<=nlstate;j++)
                   6613:         for(theta=1; theta <=npar; theta++)
                   6614:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6615:                
                   6616:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6617:        for(theta=1; theta <=npar; theta++)
                   6618:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6619:      /**< as well as its transposed matrix 
                   6620:       */               
1.218     brouard  6621:                
                   6622:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6623:      for(i=1;i<=nlstate;i++)
                   6624:        for(j=1;j<=nlstate;j++)
                   6625:         vareij[i][j][(int)age] =0.;
1.279     brouard  6626: 
                   6627:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6628:       * and k (nhstepm) formula 15 of article
                   6629:       * Lievre-Brouard-Heathcote
                   6630:       */
                   6631:      
1.218     brouard  6632:      for(h=0;h<=nhstepm;h++){
                   6633:        for(k=0;k<=nhstepm;k++){
                   6634:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6635:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6636:         for(i=1;i<=nlstate;i++)
                   6637:           for(j=1;j<=nlstate;j++)
                   6638:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6639:        }
                   6640:      }
                   6641:                
1.279     brouard  6642:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6643:       * p.j overall mortality formula 49 but computed directly because
                   6644:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6645:       * wix is independent of theta.
                   6646:       */
1.218     brouard  6647:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6648:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6649:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6650:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6651:         varppt[j][i]=doldmp[j][i];
                   6652:      /* end ppptj */
                   6653:      /*  x centered again */
                   6654:                
1.242     brouard  6655:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6656:                
                   6657:      if (popbased==1) {
                   6658:        if(mobilav ==0){
                   6659:         for(i=1; i<=nlstate;i++)
                   6660:           prlim[i][i]=probs[(int)age][i][ij];
                   6661:        }else{ /* mobilav */ 
                   6662:         for(i=1; i<=nlstate;i++)
                   6663:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6664:        }
                   6665:      }
                   6666:                
                   6667:      /* This for computing probability of death (h=1 means
                   6668:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6669:        as a weighted average of prlim.
                   6670:      */
1.235     brouard  6671:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6672:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6673:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6674:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6675:      }    
                   6676:      /* end probability of death */
                   6677:                
                   6678:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6679:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6680:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6681:        for(i=1; i<=nlstate;i++){
                   6682:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6683:        }
                   6684:      } 
                   6685:      fprintf(ficresprobmorprev,"\n");
                   6686:                
                   6687:      fprintf(ficresvij,"%.0f ",age );
                   6688:      for(i=1; i<=nlstate;i++)
                   6689:        for(j=1; j<=nlstate;j++){
                   6690:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6691:        }
                   6692:      fprintf(ficresvij,"\n");
                   6693:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6694:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6695:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6696:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6697:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6698:    } /* End age */
                   6699:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6700:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6701:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6702:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6703:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6704:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6705:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6706:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6707:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6708:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6709:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6710:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6711:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6712:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6713:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6714:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6715:    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);
                   6716:    /*  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  6717:     */
1.218     brouard  6718:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6719:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6720: 
1.218     brouard  6721:    free_vector(xp,1,npar);
                   6722:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6723:    free_matrix(dnewm,1,nlstate,1,npar);
                   6724:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6725:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6726:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6727:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6728:    fclose(ficresprobmorprev);
                   6729:    fflush(ficgp);
                   6730:    fflush(fichtm); 
                   6731:  }  /* end varevsij */
1.126     brouard  6732: 
                   6733: /************ Variance of prevlim ******************/
1.269     brouard  6734:  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  6735: {
1.205     brouard  6736:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6737:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6738: 
1.268     brouard  6739:   double **dnewmpar,**doldm;
1.126     brouard  6740:   int i, j, nhstepm, hstepm;
                   6741:   double *xp;
                   6742:   double *gp, *gm;
                   6743:   double **gradg, **trgradg;
1.208     brouard  6744:   double **mgm, **mgp;
1.126     brouard  6745:   double age,agelim;
                   6746:   int theta;
                   6747:   
                   6748:   pstamp(ficresvpl);
1.288     brouard  6749:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6750:   fprintf(ficresvpl,"# Age ");
                   6751:   if(nresult >=1)
                   6752:     fprintf(ficresvpl," Result# ");
1.126     brouard  6753:   for(i=1; i<=nlstate;i++)
                   6754:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6755:   fprintf(ficresvpl,"\n");
                   6756: 
                   6757:   xp=vector(1,npar);
1.268     brouard  6758:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6759:   doldm=matrix(1,nlstate,1,nlstate);
                   6760:   
                   6761:   hstepm=1*YEARM; /* Every year of age */
                   6762:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6763:   agelim = AGESUP;
                   6764:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6765:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6766:     if (stepm >= YEARM) hstepm=1;
                   6767:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6768:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6769:     mgp=matrix(1,npar,1,nlstate);
                   6770:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6771:     gp=vector(1,nlstate);
                   6772:     gm=vector(1,nlstate);
                   6773: 
                   6774:     for(theta=1; theta <=npar; theta++){
                   6775:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6776:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6777:       }
1.288     brouard  6778:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6779:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6780:       /* else */
                   6781:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6782:       for(i=1;i<=nlstate;i++){
1.126     brouard  6783:        gp[i] = prlim[i][i];
1.208     brouard  6784:        mgp[theta][i] = prlim[i][i];
                   6785:       }
1.126     brouard  6786:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6787:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6788:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6789:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6790:       /* else */
                   6791:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6792:       for(i=1;i<=nlstate;i++){
1.126     brouard  6793:        gm[i] = prlim[i][i];
1.208     brouard  6794:        mgm[theta][i] = prlim[i][i];
                   6795:       }
1.126     brouard  6796:       for(i=1;i<=nlstate;i++)
                   6797:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6798:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6799:     } /* End theta */
                   6800: 
                   6801:     trgradg =matrix(1,nlstate,1,npar);
                   6802: 
                   6803:     for(j=1; j<=nlstate;j++)
                   6804:       for(theta=1; theta <=npar; theta++)
                   6805:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6806:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6807:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6808:     /*   for(j=1; j<=nlstate;j++){ */
                   6809:     /*         printf(" %d ",j); */
                   6810:     /*         for(theta=1; theta <=npar; theta++) */
                   6811:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6812:     /*         printf("\n "); */
                   6813:     /*   } */
                   6814:     /* } */
                   6815:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6816:     /*   printf("\n gradg %d ",(int)age); */
                   6817:     /*   for(j=1; j<=nlstate;j++){ */
                   6818:     /*         printf("%d ",j); */
                   6819:     /*         for(theta=1; theta <=npar; theta++) */
                   6820:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6821:     /*         printf("\n "); */
                   6822:     /*   } */
                   6823:     /* } */
1.126     brouard  6824: 
                   6825:     for(i=1;i<=nlstate;i++)
                   6826:       varpl[i][(int)age] =0.;
1.209     brouard  6827:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6828:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6829:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6830:     }else{
1.268     brouard  6831:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6832:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6833:     }
1.126     brouard  6834:     for(i=1;i<=nlstate;i++)
                   6835:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6836: 
                   6837:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6838:     if(nresult >=1)
                   6839:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6840:     for(i=1; i<=nlstate;i++){
1.126     brouard  6841:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6842:       /* for(j=1;j<=nlstate;j++) */
                   6843:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6844:     }
1.126     brouard  6845:     fprintf(ficresvpl,"\n");
                   6846:     free_vector(gp,1,nlstate);
                   6847:     free_vector(gm,1,nlstate);
1.208     brouard  6848:     free_matrix(mgm,1,npar,1,nlstate);
                   6849:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6850:     free_matrix(gradg,1,npar,1,nlstate);
                   6851:     free_matrix(trgradg,1,nlstate,1,npar);
                   6852:   } /* End age */
                   6853: 
                   6854:   free_vector(xp,1,npar);
                   6855:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6856:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6857: 
                   6858: }
                   6859: 
                   6860: 
                   6861: /************ Variance of backprevalence limit ******************/
1.269     brouard  6862:  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  6863: {
                   6864:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6865:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6866: 
                   6867:   double **dnewmpar,**doldm;
                   6868:   int i, j, nhstepm, hstepm;
                   6869:   double *xp;
                   6870:   double *gp, *gm;
                   6871:   double **gradg, **trgradg;
                   6872:   double **mgm, **mgp;
                   6873:   double age,agelim;
                   6874:   int theta;
                   6875:   
                   6876:   pstamp(ficresvbl);
                   6877:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6878:   fprintf(ficresvbl,"# Age ");
                   6879:   if(nresult >=1)
                   6880:     fprintf(ficresvbl," Result# ");
                   6881:   for(i=1; i<=nlstate;i++)
                   6882:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6883:   fprintf(ficresvbl,"\n");
                   6884: 
                   6885:   xp=vector(1,npar);
                   6886:   dnewmpar=matrix(1,nlstate,1,npar);
                   6887:   doldm=matrix(1,nlstate,1,nlstate);
                   6888:   
                   6889:   hstepm=1*YEARM; /* Every year of age */
                   6890:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6891:   agelim = AGEINF;
                   6892:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6893:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6894:     if (stepm >= YEARM) hstepm=1;
                   6895:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6896:     gradg=matrix(1,npar,1,nlstate);
                   6897:     mgp=matrix(1,npar,1,nlstate);
                   6898:     mgm=matrix(1,npar,1,nlstate);
                   6899:     gp=vector(1,nlstate);
                   6900:     gm=vector(1,nlstate);
                   6901: 
                   6902:     for(theta=1; theta <=npar; theta++){
                   6903:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6904:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6905:       }
                   6906:       if(mobilavproj > 0 )
                   6907:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6908:       else
                   6909:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6910:       for(i=1;i<=nlstate;i++){
                   6911:        gp[i] = bprlim[i][i];
                   6912:        mgp[theta][i] = bprlim[i][i];
                   6913:       }
                   6914:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6915:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6916:        if(mobilavproj > 0 )
                   6917:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6918:        else
                   6919:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6920:       for(i=1;i<=nlstate;i++){
                   6921:        gm[i] = bprlim[i][i];
                   6922:        mgm[theta][i] = bprlim[i][i];
                   6923:       }
                   6924:       for(i=1;i<=nlstate;i++)
                   6925:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6926:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6927:     } /* End theta */
                   6928: 
                   6929:     trgradg =matrix(1,nlstate,1,npar);
                   6930: 
                   6931:     for(j=1; j<=nlstate;j++)
                   6932:       for(theta=1; theta <=npar; theta++)
                   6933:        trgradg[j][theta]=gradg[theta][j];
                   6934:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6935:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6936:     /*   for(j=1; j<=nlstate;j++){ */
                   6937:     /*         printf(" %d ",j); */
                   6938:     /*         for(theta=1; theta <=npar; theta++) */
                   6939:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6940:     /*         printf("\n "); */
                   6941:     /*   } */
                   6942:     /* } */
                   6943:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6944:     /*   printf("\n gradg %d ",(int)age); */
                   6945:     /*   for(j=1; j<=nlstate;j++){ */
                   6946:     /*         printf("%d ",j); */
                   6947:     /*         for(theta=1; theta <=npar; theta++) */
                   6948:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6949:     /*         printf("\n "); */
                   6950:     /*   } */
                   6951:     /* } */
                   6952: 
                   6953:     for(i=1;i<=nlstate;i++)
                   6954:       varbpl[i][(int)age] =0.;
                   6955:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6956:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6957:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6958:     }else{
                   6959:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6960:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6961:     }
                   6962:     for(i=1;i<=nlstate;i++)
                   6963:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6964: 
                   6965:     fprintf(ficresvbl,"%.0f ",age );
                   6966:     if(nresult >=1)
                   6967:       fprintf(ficresvbl,"%d ",nres );
                   6968:     for(i=1; i<=nlstate;i++)
                   6969:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6970:     fprintf(ficresvbl,"\n");
                   6971:     free_vector(gp,1,nlstate);
                   6972:     free_vector(gm,1,nlstate);
                   6973:     free_matrix(mgm,1,npar,1,nlstate);
                   6974:     free_matrix(mgp,1,npar,1,nlstate);
                   6975:     free_matrix(gradg,1,npar,1,nlstate);
                   6976:     free_matrix(trgradg,1,nlstate,1,npar);
                   6977:   } /* End age */
                   6978: 
                   6979:   free_vector(xp,1,npar);
                   6980:   free_matrix(doldm,1,nlstate,1,npar);
                   6981:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6982: 
                   6983: }
                   6984: 
                   6985: /************ Variance of one-step probabilities  ******************/
                   6986: 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  6987:  {
                   6988:    int i, j=0,  k1, l1, tj;
                   6989:    int k2, l2, j1,  z1;
                   6990:    int k=0, l;
                   6991:    int first=1, first1, first2;
1.326     brouard  6992:    int nres=0; /* New */
1.222     brouard  6993:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6994:    double **dnewm,**doldm;
                   6995:    double *xp;
                   6996:    double *gp, *gm;
                   6997:    double **gradg, **trgradg;
                   6998:    double **mu;
                   6999:    double age, cov[NCOVMAX+1];
                   7000:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7001:    int theta;
                   7002:    char fileresprob[FILENAMELENGTH];
                   7003:    char fileresprobcov[FILENAMELENGTH];
                   7004:    char fileresprobcor[FILENAMELENGTH];
                   7005:    double ***varpij;
                   7006: 
                   7007:    strcpy(fileresprob,"PROB_"); 
                   7008:    strcat(fileresprob,fileres);
                   7009:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7010:      printf("Problem with resultfile: %s\n", fileresprob);
                   7011:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7012:    }
                   7013:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7014:    strcat(fileresprobcov,fileresu);
                   7015:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7016:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7017:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7018:    }
                   7019:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7020:    strcat(fileresprobcor,fileresu);
                   7021:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7022:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7023:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7024:    }
                   7025:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7026:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7027:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7028:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7029:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7030:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7031:    pstamp(ficresprob);
                   7032:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7033:    fprintf(ficresprob,"# Age");
                   7034:    pstamp(ficresprobcov);
                   7035:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7036:    fprintf(ficresprobcov,"# Age");
                   7037:    pstamp(ficresprobcor);
                   7038:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7039:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7040: 
                   7041: 
1.222     brouard  7042:    for(i=1; i<=nlstate;i++)
                   7043:      for(j=1; j<=(nlstate+ndeath);j++){
                   7044:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7045:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7046:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7047:      }  
                   7048:    /* fprintf(ficresprob,"\n");
                   7049:       fprintf(ficresprobcov,"\n");
                   7050:       fprintf(ficresprobcor,"\n");
                   7051:    */
                   7052:    xp=vector(1,npar);
                   7053:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7054:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7055:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7056:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7057:    first=1;
                   7058:    fprintf(ficgp,"\n# Routine varprob");
                   7059:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7060:    fprintf(fichtm,"\n");
                   7061: 
1.288     brouard  7062:    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  7063:    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);
                   7064:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7065: and drawn. It helps understanding how is the covariance between two incidences.\
                   7066:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7067:    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  7068: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7069: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7070: standard deviations wide on each axis. <br>\
                   7071:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7072:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7073: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7074: 
1.222     brouard  7075:    cov[1]=1;
                   7076:    /* tj=cptcoveff; */
1.225     brouard  7077:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7078:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7079:    j1=0;
1.332     brouard  7080: 
                   7081:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7082:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
                   7083:      printf("Varprob  TKresult[nres]=%d j1=%d, nres=%d, cptcovn=%d, cptcoveff=%d tj=%d \n",  TKresult[nres], j1, nres, cptcovn, cptcoveff, tj);
                   7084:      if(tj != 1 && TKresult[nres]!= j1)
                   7085:        continue;
                   7086: 
                   7087:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7088:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7089:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7090:      if  (cptcovn>0) {
                   7091:        fprintf(ficresprob, "\n#********** Variable "); 
1.332     brouard  7092:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7093:        fprintf(ficresprob, "**********\n#\n");
                   7094:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.332     brouard  7095:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7096:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  7097:                        
1.222     brouard  7098:        fprintf(ficgp, "\n#********** Variable "); 
1.332     brouard  7099:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7100:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  7101:                        
                   7102:                        
1.222     brouard  7103:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.319     brouard  7104:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]); */
1.332     brouard  7105:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtmcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7106:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7107:                        
1.222     brouard  7108:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.332     brouard  7109:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.222     brouard  7110:        fprintf(ficresprobcor, "**********\n#");    
                   7111:        if(invalidvarcomb[j1]){
                   7112:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7113:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7114:         continue;
                   7115:        }
                   7116:      }
                   7117:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7118:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7119:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7120:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   7121:      for (age=bage; age<=fage; age ++){ 
                   7122:        cov[2]=age;
                   7123:        if(nagesqr==1)
                   7124:         cov[3]= age*age;
1.326     brouard  7125:        /* for (k=1; k<=cptcovn;k++) { */
                   7126:        /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; */
                   7127:        for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   7128:         /* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates */
1.332     brouard  7129:         cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])];
1.222     brouard  7130:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   7131:                                                                    * 1  1 1 1 1
                   7132:                                                                    * 2  2 1 1 1
                   7133:                                                                    * 3  1 2 1 1
                   7134:                                                                    */
                   7135:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   7136:        }
1.319     brouard  7137:        /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7138:        /* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] */
                   7139:        /*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.326     brouard  7140:        for (k=1; k<=cptcovage;k++){  /* For product with age */
                   7141:         if(Dummy[Tage[k]]==2){ /* dummy with age */
1.332     brouard  7142:           cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2];
1.326     brouard  7143:           /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7144:         } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
1.327     brouard  7145:           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]);
1.332     brouard  7146:           /* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\* Using the mean of quantitative variable Tvar[Tage[k]] /\* Tqresult[nres][k]; *\/ */
                   7147:           /* exit(1); */
1.326     brouard  7148:           /* cov[++k1]=Tqresult[nres][k];  */
                   7149:         }
                   7150:         /* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7151:        }
                   7152:        for (k=1; k<=cptcovprod;k++){/* For product without age */
1.329     brouard  7153:         if(Dummy[Tvard[k][1]]==0){
                   7154:           if(Dummy[Tvard[k][2]]==0){
1.332     brouard  7155:             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]])];
1.326     brouard  7156:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7157:           }else{ /* Should we use the mean of the quantitative variables? */
1.332     brouard  7158:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]];
1.326     brouard  7159:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
                   7160:           }
                   7161:         }else{
1.329     brouard  7162:           if(Dummy[Tvard[k][2]]==0){
1.332     brouard  7163:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]];
1.326     brouard  7164:             /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
                   7165:           }else{
1.332     brouard  7166:             cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]];
1.326     brouard  7167:             /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   7168:           }
                   7169:         }
                   7170:         /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7171:        }                       
                   7172: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7173:        for(theta=1; theta <=npar; theta++){
                   7174:         for(i=1; i<=npar; i++)
                   7175:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7176:                                
1.222     brouard  7177:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7178:                                
1.222     brouard  7179:         k=0;
                   7180:         for(i=1; i<= (nlstate); i++){
                   7181:           for(j=1; j<=(nlstate+ndeath);j++){
                   7182:             k=k+1;
                   7183:             gp[k]=pmmij[i][j];
                   7184:           }
                   7185:         }
1.220     brouard  7186:                                
1.222     brouard  7187:         for(i=1; i<=npar; i++)
                   7188:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7189:                                
1.222     brouard  7190:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7191:         k=0;
                   7192:         for(i=1; i<=(nlstate); i++){
                   7193:           for(j=1; j<=(nlstate+ndeath);j++){
                   7194:             k=k+1;
                   7195:             gm[k]=pmmij[i][j];
                   7196:           }
                   7197:         }
1.220     brouard  7198:                                
1.222     brouard  7199:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7200:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7201:        }
1.126     brouard  7202: 
1.222     brouard  7203:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7204:         for(theta=1; theta <=npar; theta++)
                   7205:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7206:                        
1.222     brouard  7207:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7208:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7209:                        
1.222     brouard  7210:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7211:                        
1.222     brouard  7212:        k=0;
                   7213:        for(i=1; i<=(nlstate); i++){
                   7214:         for(j=1; j<=(nlstate+ndeath);j++){
                   7215:           k=k+1;
                   7216:           mu[k][(int) age]=pmmij[i][j];
                   7217:         }
                   7218:        }
                   7219:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7220:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7221:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7222:                        
1.222     brouard  7223:        /*printf("\n%d ",(int)age);
                   7224:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7225:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7226:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7227:         }*/
1.220     brouard  7228:                        
1.222     brouard  7229:        fprintf(ficresprob,"\n%d ",(int)age);
                   7230:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7231:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7232:                        
1.222     brouard  7233:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7234:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7235:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7236:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7237:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7238:        }
                   7239:        i=0;
                   7240:        for (k=1; k<=(nlstate);k++){
                   7241:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7242:           i++;
                   7243:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7244:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7245:           for (j=1; j<=i;j++){
                   7246:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7247:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7248:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7249:           }
                   7250:         }
                   7251:        }/* end of loop for state */
                   7252:      } /* end of loop for age */
                   7253:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7254:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7255:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7256:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7257:     
                   7258:      /* Confidence intervalle of pij  */
                   7259:      /*
                   7260:        fprintf(ficgp,"\nunset parametric;unset label");
                   7261:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7262:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7263:        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);
                   7264:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7265:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7266:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7267:      */
                   7268:                
                   7269:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7270:      first1=1;first2=2;
                   7271:      for (k2=1; k2<=(nlstate);k2++){
                   7272:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7273:         if(l2==k2) continue;
                   7274:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7275:         for (k1=1; k1<=(nlstate);k1++){
                   7276:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7277:             if(l1==k1) continue;
                   7278:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7279:             if(i<=j) continue;
                   7280:             for (age=bage; age<=fage; age ++){ 
                   7281:               if ((int)age %5==0){
                   7282:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7283:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7284:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7285:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7286:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7287:                 c12=cv12/sqrt(v1*v2);
                   7288:                 /* Computing eigen value of matrix of covariance */
                   7289:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7290:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7291:                 if ((lc2 <0) || (lc1 <0) ){
                   7292:                   if(first2==1){
                   7293:                     first1=0;
                   7294:                     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);
                   7295:                   }
                   7296:                   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);
                   7297:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7298:                   /* lc2=fabs(lc2); */
                   7299:                 }
1.220     brouard  7300:                                                                
1.222     brouard  7301:                 /* Eigen vectors */
1.280     brouard  7302:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7303:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7304:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7305:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7306:                 }else
                   7307:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7308:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7309:                 v21=(lc1-v1)/cv12*v11;
                   7310:                 v12=-v21;
                   7311:                 v22=v11;
                   7312:                 tnalp=v21/v11;
                   7313:                 if(first1==1){
                   7314:                   first1=0;
                   7315:                   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);
                   7316:                 }
                   7317:                 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);
                   7318:                 /*printf(fignu*/
                   7319:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7320:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7321:                 if(first==1){
                   7322:                   first=0;
                   7323:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7324:                   fprintf(ficgp,"\nset parametric;unset label");
                   7325:                   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);
                   7326:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7327:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7328:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7329: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7330:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7331:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7332:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7333:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7334:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7335:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7336:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7337:                   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  7338:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7339:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7340:                 }else{
                   7341:                   first=0;
                   7342:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7343:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7344:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7345:                   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  7346:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7347:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7348:                 }/* if first */
                   7349:               } /* age mod 5 */
                   7350:             } /* end loop age */
                   7351:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7352:             first=1;
                   7353:           } /*l12 */
                   7354:         } /* k12 */
                   7355:        } /*l1 */
                   7356:      }/* k1 */
1.332     brouard  7357:    }  /* loop on combination of covariates j1 */
1.326     brouard  7358:    } /* loop on nres */
1.222     brouard  7359:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7360:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7361:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7362:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7363:    free_vector(xp,1,npar);
                   7364:    fclose(ficresprob);
                   7365:    fclose(ficresprobcov);
                   7366:    fclose(ficresprobcor);
                   7367:    fflush(ficgp);
                   7368:    fflush(fichtmcov);
                   7369:  }
1.126     brouard  7370: 
                   7371: 
                   7372: /******************* Printing html file ***********/
1.201     brouard  7373: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7374:                  int lastpass, int stepm, int weightopt, char model[],\
                   7375:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7376:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7377:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7378:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7379:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7380:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7381:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7382:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7383: </ul>");
1.319     brouard  7384: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7385: /* </ul>", model); */
1.214     brouard  7386:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7387:    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",
                   7388:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7389:    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  7390:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7391:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7392:    fprintf(fichtm,"\
                   7393:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7394:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7395:    fprintf(fichtm,"\
1.217     brouard  7396:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7397:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7398:    fprintf(fichtm,"\
1.288     brouard  7399:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7400:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7401:    fprintf(fichtm,"\
1.288     brouard  7402:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7403:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7404:    fprintf(fichtm,"\
1.211     brouard  7405:  - (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  7406:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7407:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7408:    if(prevfcast==1){
                   7409:      fprintf(fichtm,"\
                   7410:  - Prevalence projections by age and states:                           \
1.201     brouard  7411:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7412:    }
1.126     brouard  7413: 
                   7414: 
1.225     brouard  7415:    m=pow(2,cptcoveff);
1.222     brouard  7416:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7417: 
1.317     brouard  7418:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7419: 
                   7420:    jj1=0;
                   7421: 
                   7422:    fprintf(fichtm," \n<ul>");
                   7423:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7424:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7425:      if(m != 1 && TKresult[nres]!= k1)
                   7426:        continue;
                   7427:      jj1++;
                   7428:      if (cptcovn > 0) {
                   7429:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7430:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7431:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7432:        }
                   7433:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7434:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7435:        }
                   7436:        fprintf(fichtm,"\">");
                   7437:        
                   7438:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7439:        fprintf(fichtm,"************ Results for covariates");
                   7440:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7441:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7442:        }
                   7443:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7444:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7445:        }
                   7446:        if(invalidvarcomb[k1]){
                   7447:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7448:         continue;
                   7449:        }
                   7450:        fprintf(fichtm,"</a></li>");
                   7451:      } /* cptcovn >0 */
                   7452:    }
1.317     brouard  7453:    fprintf(fichtm," \n</ul>");
1.264     brouard  7454: 
1.222     brouard  7455:    jj1=0;
1.237     brouard  7456: 
                   7457:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7458:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7459:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7460:        continue;
1.220     brouard  7461: 
1.222     brouard  7462:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7463:      jj1++;
                   7464:      if (cptcovn > 0) {
1.264     brouard  7465:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7466:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7467:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7468:        }
                   7469:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7470:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7471:        }
                   7472:        fprintf(fichtm,"\"</a>");
                   7473:  
1.222     brouard  7474:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7475:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7476:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7477:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7478:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7479:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7480:        }
1.237     brouard  7481:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7482:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7483:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7484:       }
                   7485:        
1.230     brouard  7486:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7487:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7488:        if(invalidvarcomb[k1]){
                   7489:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7490:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7491:         continue;
                   7492:        }
                   7493:      }
                   7494:      /* aij, bij */
1.259     brouard  7495:      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  7496: <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  7497:      /* Pij */
1.241     brouard  7498:      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> \
                   7499: <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  7500:      /* Quasi-incidences */
                   7501:      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  7502:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7503:  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  7504: 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> \
                   7505: <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  7506:      /* Survival functions (period) in state j */
                   7507:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7508:        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);
                   7509:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7510:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7511:      }
                   7512:      /* State specific survival functions (period) */
                   7513:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7514:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7515:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7516:  <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);
                   7517:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7518:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7519:      }
1.288     brouard  7520:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7521:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7522:        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);
                   7523:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7524:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7525:      }
1.296     brouard  7526:      if(prevbcast==1){
1.288     brouard  7527:        /* Backward prevalence in each health state */
1.222     brouard  7528:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7529:         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> \
1.241     brouard  7530: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7531:        }
1.217     brouard  7532:      }
1.222     brouard  7533:      if(prevfcast==1){
1.288     brouard  7534:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7535:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7536:         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);
                   7537:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7538:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7539:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7540:        }
                   7541:      }
1.296     brouard  7542:      if(prevbcast==1){
1.268     brouard  7543:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7544:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7545:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7546:  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 \
                   7547:  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  7548: 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);
                   7549:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7550:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7551:        }
                   7552:      }
1.220     brouard  7553:         
1.222     brouard  7554:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7555:        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);
                   7556:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7557:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7558:      }
                   7559:      /* } /\* end i1 *\/ */
                   7560:    }/* End k1 */
                   7561:    fprintf(fichtm,"</ul>");
1.126     brouard  7562: 
1.222     brouard  7563:    fprintf(fichtm,"\
1.126     brouard  7564: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7565:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7566:  - 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  7567: But because parameters are usually highly correlated (a higher incidence of disability \
                   7568: and a higher incidence of recovery can give very close observed transition) it might \
                   7569: be very useful to look not only at linear confidence intervals estimated from the \
                   7570: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7571: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7572: covariance matrix of the one-step probabilities. \
                   7573: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7574: 
1.222     brouard  7575:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7576:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7577:    fprintf(fichtm,"\
1.126     brouard  7578:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7579:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7580: 
1.222     brouard  7581:    fprintf(fichtm,"\
1.126     brouard  7582:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7583:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7584:    fprintf(fichtm,"\
1.126     brouard  7585:  - 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): \
                   7586:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7587:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7588:    fprintf(fichtm,"\
1.126     brouard  7589:  - (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): \
                   7590:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7591:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7592:    fprintf(fichtm,"\
1.288     brouard  7593:  - 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  7594:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7595:    fprintf(fichtm,"\
1.128     brouard  7596:  - 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  7597:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7598:    fprintf(fichtm,"\
1.288     brouard  7599:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7600:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7601: 
                   7602: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7603: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7604: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7605: /*     <br>",fileres,fileres,fileres,fileres); */
                   7606: /*  else  */
                   7607: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
1.222     brouard  7608:    fflush(fichtm);
1.126     brouard  7609: 
1.225     brouard  7610:    m=pow(2,cptcoveff);
1.222     brouard  7611:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7612: 
1.317     brouard  7613:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7614: 
                   7615:   jj1=0;
                   7616: 
                   7617:    fprintf(fichtm," \n<ul>");
                   7618:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7619:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7620:      if(m != 1 && TKresult[nres]!= k1)
                   7621:        continue;
                   7622:      jj1++;
                   7623:      if (cptcovn > 0) {
                   7624:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7625:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7626:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7627:        }
                   7628:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7629:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7630:        }
                   7631:        fprintf(fichtm,"\">");
                   7632:        
                   7633:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7634:        fprintf(fichtm,"************ Results for covariates");
                   7635:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7636:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7637:        }
                   7638:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7639:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7640:        }
                   7641:        if(invalidvarcomb[k1]){
                   7642:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7643:         continue;
                   7644:        }
                   7645:        fprintf(fichtm,"</a></li>");
                   7646:      } /* cptcovn >0 */
                   7647:    }
                   7648:    fprintf(fichtm," \n</ul>");
                   7649: 
1.222     brouard  7650:    jj1=0;
1.237     brouard  7651: 
1.241     brouard  7652:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7653:    for(k1=1; k1<=m;k1++){
1.253     brouard  7654:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7655:        continue;
1.222     brouard  7656:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7657:      jj1++;
1.126     brouard  7658:      if (cptcovn > 0) {
1.317     brouard  7659:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7660:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7661:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7662:        }
                   7663:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7664:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7665:        }
                   7666:        fprintf(fichtm,"\"</a>");
                   7667:        
1.126     brouard  7668:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7669:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7670:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7671:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7672:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7673:        }
1.237     brouard  7674:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7675:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7676:       }
                   7677: 
1.321     brouard  7678:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7679: 
1.222     brouard  7680:        if(invalidvarcomb[k1]){
                   7681:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7682:         continue;
                   7683:        }
1.126     brouard  7684:      }
                   7685:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7686:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7687: 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);
                   7688:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7689:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7690:      }
                   7691:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7692: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7693: true period expectancies (those weighted with period prevalences are also\
                   7694:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7695:  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);
                   7696:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7697:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7698:      /* } /\* end i1 *\/ */
                   7699:    }/* End k1 */
1.241     brouard  7700:   }/* End nres */
1.222     brouard  7701:    fprintf(fichtm,"</ul>");
                   7702:    fflush(fichtm);
1.126     brouard  7703: }
                   7704: 
                   7705: /******************* Gnuplot file **************/
1.296     brouard  7706: 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  7707: 
                   7708:   char dirfileres[132],optfileres[132];
1.264     brouard  7709:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7710:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
1.211     brouard  7711:   int lv=0, vlv=0, kl=0;
1.130     brouard  7712:   int ng=0;
1.201     brouard  7713:   int vpopbased;
1.223     brouard  7714:   int ioffset; /* variable offset for columns */
1.270     brouard  7715:   int iyearc=1; /* variable column for year of projection  */
                   7716:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7717:   int nres=0; /* Index of resultline */
1.266     brouard  7718:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7719: 
1.126     brouard  7720: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7721: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7722: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7723: /*   } */
                   7724: 
                   7725:   /*#ifdef windows */
                   7726:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7727:   /*#endif */
1.225     brouard  7728:   m=pow(2,cptcoveff);
1.126     brouard  7729: 
1.274     brouard  7730:   /* diagram of the model */
                   7731:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7732:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7733:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7734:   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);
                   7735: 
                   7736:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] arrow (%d+1)*10+i from cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.80*(cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0)  ), -0.80*(sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) + yoff ) ls 4\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
                   7737:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7738:   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);
                   7739:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7740:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7741:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7742:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7743: 
1.202     brouard  7744:   /* Contribution to likelihood */
                   7745:   /* Plot the probability implied in the likelihood */
1.223     brouard  7746:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7747:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7748:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7749:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7750: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7751:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7752: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7753:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7754:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7755:   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));
                   7756:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7757:   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));
                   7758:   for (i=1; i<= nlstate ; i ++) {
                   7759:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7760:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7761:     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);
                   7762:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7763:       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);
                   7764:     }
                   7765:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7766:   }
                   7767:   /* 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 */               
                   7768:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7769:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7770:   fprintf(ficgp,"\nset out;unset log\n");
                   7771:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7772: 
1.126     brouard  7773:   strcpy(dirfileres,optionfilefiname);
                   7774:   strcpy(optfileres,"vpl");
1.223     brouard  7775:   /* 1eme*/
1.238     brouard  7776:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7777:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7778:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7779:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7780:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7781:          continue;
                   7782:        /* We are interested in selected combination by the resultline */
1.246     brouard  7783:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7784:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7785:        strcpy(gplotlabel,"(");
1.238     brouard  7786:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
1.332     brouard  7787:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the value of the covariate corresponding to k1 combination *\/ */
                   7788:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7789:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7790:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7791:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7792:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7793:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7794:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7795:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7796:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7797:        }
                   7798:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7799:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7800:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7801:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7802:        }
                   7803:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7804:        /* printf("\n#\n"); */
1.238     brouard  7805:        fprintf(ficgp,"\n#\n");
                   7806:        if(invalidvarcomb[k1]){
1.260     brouard  7807:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7808:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7809:          continue;
                   7810:        }
1.235     brouard  7811:       
1.241     brouard  7812:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7813:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7814:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
1.321     brouard  7815:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7816:        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);
                   7817:        /* 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); */
                   7818:       /* k1-1 error should be nres-1*/
1.238     brouard  7819:        for (i=1; i<= nlstate ; i ++) {
                   7820:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7821:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7822:        }
1.288     brouard  7823:        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  7824:        for (i=1; i<= nlstate ; i ++) {
                   7825:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7826:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7827:        } 
1.260     brouard  7828:        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  7829:        for (i=1; i<= nlstate ; i ++) {
                   7830:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7831:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7832:        }  
1.265     brouard  7833:        /* 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)); */
                   7834:        
                   7835:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7836:         if(cptcoveff ==0){
1.271     brouard  7837:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7838:        }else{
                   7839:          kl=0;
                   7840:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7841:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7842:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  7843:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7844:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7845:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7846:            vlv= nbcode[Tvaraff[k]][lv];
                   7847:            kl++;
                   7848:            /* 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 *\/ */
                   7849:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7850:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7851:            /* ''  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*/
                   7852:            if(k==cptcoveff){
                   7853:              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], \
                   7854:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7855:            }else{
                   7856:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7857:              kl++;
                   7858:            }
                   7859:          } /* end covariate */
                   7860:        } /* end if no covariate */
                   7861: 
1.296     brouard  7862:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7863:          /* 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  7864:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7865:          if(cptcoveff ==0){
1.245     brouard  7866:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7867:          }else{
                   7868:            kl=0;
                   7869:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7870:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7871:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7872:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7873:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7874:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  7875:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   7876:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  7877:              kl++;
1.238     brouard  7878:              /* 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 *\/ */
                   7879:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7880:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7881:              /* ''  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*/
                   7882:              if(k==cptcoveff){
1.245     brouard  7883:                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  7884:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7885:              }else{
1.332     brouard  7886:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  7887:                kl++;
                   7888:              }
                   7889:            } /* end covariate */
                   7890:          } /* end if no covariate */
1.296     brouard  7891:          if(prevbcast == 1){
1.268     brouard  7892:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7893:            /* k1-1 error should be nres-1*/
                   7894:            for (i=1; i<= nlstate ; i ++) {
                   7895:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7896:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7897:            }
1.271     brouard  7898:            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  7899:            for (i=1; i<= nlstate ; i ++) {
                   7900:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7901:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7902:            } 
1.276     brouard  7903:            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  7904:            for (i=1; i<= nlstate ; i ++) {
                   7905:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7906:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7907:            } 
1.274     brouard  7908:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7909:          } /* end if backprojcast */
1.296     brouard  7910:        } /* end if prevbcast */
1.276     brouard  7911:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7912:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7913:       } /* nres */
1.201     brouard  7914:     } /* k1 */
                   7915:   } /* cpt */
1.235     brouard  7916: 
                   7917:   
1.126     brouard  7918:   /*2 eme*/
1.238     brouard  7919:   for (k1=1; k1<= m ; k1 ++){  
                   7920:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7921:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7922:        continue;
                   7923:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7924:       strcpy(gplotlabel,"(");
1.238     brouard  7925:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  7926:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   7927:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.223     brouard  7928:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7929:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7930:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  7931:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   7932:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  7933:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7934:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7935:       }
1.237     brouard  7936:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7937:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7938:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7939:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7940:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7941:       }
1.264     brouard  7942:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7943:       fprintf(ficgp,"\n#\n");
1.223     brouard  7944:       if(invalidvarcomb[k1]){
                   7945:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7946:        continue;
                   7947:       }
1.219     brouard  7948:                        
1.241     brouard  7949:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7950:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7951:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7952:        if(vpopbased==0){
1.238     brouard  7953:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7954:        }else
1.238     brouard  7955:          fprintf(ficgp,"\nreplot ");
                   7956:        for (i=1; i<= nlstate+1 ; i ++) {
                   7957:          k=2*i;
1.261     brouard  7958:          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  7959:          for (j=1; j<= nlstate+1 ; j ++) {
                   7960:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7961:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7962:          }   
                   7963:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7964:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7965:          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  7966:          for (j=1; j<= nlstate+1 ; j ++) {
                   7967:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7968:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7969:          }   
                   7970:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7971:          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  7972:          for (j=1; j<= nlstate+1 ; j ++) {
                   7973:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7974:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7975:          }   
                   7976:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7977:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7978:        } /* state */
                   7979:       } /* vpopbased */
1.264     brouard  7980:       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  7981:     } /* end nres */
                   7982:   } /* k1 end 2 eme*/
                   7983:        
                   7984:        
                   7985:   /*3eme*/
                   7986:   for (k1=1; k1<= m ; k1 ++){
                   7987:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7988:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7989:        continue;
                   7990: 
1.332     brouard  7991:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  7992:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7993:        strcpy(gplotlabel,"(");
1.238     brouard  7994:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  7995:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   7996:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.238     brouard  7997:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7998:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7999:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8000:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8001:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8002:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8003:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8004:        }
                   8005:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8006:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
                   8007:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8008:        }       
1.264     brouard  8009:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8010:        fprintf(ficgp,"\n#\n");
                   8011:        if(invalidvarcomb[k1]){
                   8012:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8013:          continue;
                   8014:        }
                   8015:                        
                   8016:        /*       k=2+nlstate*(2*cpt-2); */
                   8017:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8018:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8019:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8020:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8021: 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  8022:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8023:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8024:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8025:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8026:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8027:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8028:                                
1.238     brouard  8029:        */
                   8030:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8031:          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  8032:          /*    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  8033:                                
1.238     brouard  8034:        } 
1.261     brouard  8035:        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  8036:       }
1.264     brouard  8037:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8038:     } /* end nres */
                   8039:   } /* end kl 3eme */
1.126     brouard  8040:   
1.223     brouard  8041:   /* 4eme */
1.201     brouard  8042:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  8043:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   8044:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8045:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  8046:        continue;
1.238     brouard  8047:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8048:        strcpy(gplotlabel,"(");
1.238     brouard  8049:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   8050:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8051:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8052:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8053:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8054:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8055:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8056:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8057:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8058:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8059:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8060:        }
                   8061:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8062:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8063:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8064:        }       
1.264     brouard  8065:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8066:        fprintf(ficgp,"\n#\n");
                   8067:        if(invalidvarcomb[k1]){
                   8068:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8069:          continue;
1.223     brouard  8070:        }
1.238     brouard  8071:       
1.241     brouard  8072:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8073:        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  8074:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8075: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8076:        k=3;
                   8077:        for (i=1; i<= nlstate ; i ++){
                   8078:          if(i==1){
                   8079:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8080:          }else{
                   8081:            fprintf(ficgp,", '' ");
                   8082:          }
                   8083:          l=(nlstate+ndeath)*(i-1)+1;
                   8084:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8085:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8086:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8087:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8088:        } /* nlstate */
1.264     brouard  8089:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8090:       } /* end cpt state*/ 
                   8091:     } /* end nres */
                   8092:   } /* end covariate k1 */  
                   8093: 
1.220     brouard  8094: /* 5eme */
1.201     brouard  8095:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  8096:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   8097:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8098:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  8099:        continue;
1.238     brouard  8100:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8101:        strcpy(gplotlabel,"(");
1.238     brouard  8102:        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);
                   8103:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8104:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8105:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8106:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8107:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8108:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8109:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8110:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8111:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8112:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8113:        }
                   8114:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8115:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8116:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8117:        }       
1.264     brouard  8118:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8119:        fprintf(ficgp,"\n#\n");
                   8120:        if(invalidvarcomb[k1]){
                   8121:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8122:          continue;
                   8123:        }
1.227     brouard  8124:       
1.241     brouard  8125:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8126:        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  8127:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8128: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8129:        k=3;
                   8130:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8131:          if(j==1)
                   8132:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8133:          else
                   8134:            fprintf(ficgp,", '' ");
                   8135:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8136:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8137:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8138:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8139:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8140:        } /* nlstate */
                   8141:        fprintf(ficgp,", '' ");
                   8142:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8143:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8144:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8145:          if(j < nlstate)
                   8146:            fprintf(ficgp,"$%d +",k+l);
                   8147:          else
                   8148:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8149:        }
1.264     brouard  8150:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8151:       } /* end cpt state*/ 
                   8152:     } /* end covariate */  
                   8153:   } /* end nres */
1.227     brouard  8154:   
1.220     brouard  8155: /* 6eme */
1.202     brouard  8156:   /* CV preval stable (period) for each covariate */
1.237     brouard  8157:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8158:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8159:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8160:       continue;
1.255     brouard  8161:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8162:       strcpy(gplotlabel,"(");      
1.288     brouard  8163:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  8164:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8165:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8166:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8167:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8168:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8169:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8170:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8171:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8172:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8173:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8174:       }
1.237     brouard  8175:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8176:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8177:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8178:       }        
1.264     brouard  8179:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8180:       fprintf(ficgp,"\n#\n");
1.223     brouard  8181:       if(invalidvarcomb[k1]){
1.227     brouard  8182:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8183:        continue;
1.223     brouard  8184:       }
1.227     brouard  8185:       
1.241     brouard  8186:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8187:       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  8188:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8189: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8190:       k=3; /* Offset */
1.255     brouard  8191:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8192:        if(i==1)
                   8193:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8194:        else
                   8195:          fprintf(ficgp,", '' ");
1.255     brouard  8196:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8197:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8198:        for (j=2; j<= nlstate ; j ++)
                   8199:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8200:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8201:       } /* nlstate */
1.264     brouard  8202:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8203:     } /* end cpt state*/ 
                   8204:   } /* end covariate */  
1.227     brouard  8205:   
                   8206:   
1.220     brouard  8207: /* 7eme */
1.296     brouard  8208:   if(prevbcast == 1){
1.288     brouard  8209:     /* CV backward prevalence  for each covariate */
1.237     brouard  8210:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8211:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8212:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8213:        continue;
1.268     brouard  8214:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8215:        strcpy(gplotlabel,"(");      
1.288     brouard  8216:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8217:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8218:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8219:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8220:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8221:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8222:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8223:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8224:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8225:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8226:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8227:        }
1.237     brouard  8228:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8229:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8230:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8231:        }       
1.264     brouard  8232:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8233:        fprintf(ficgp,"\n#\n");
                   8234:        if(invalidvarcomb[k1]){
                   8235:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8236:          continue;
                   8237:        }
                   8238:        
1.241     brouard  8239:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8240:        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  8241:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8242: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8243:        k=3; /* Offset */
1.268     brouard  8244:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8245:          if(i==1)
                   8246:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8247:          else
                   8248:            fprintf(ficgp,", '' ");
                   8249:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8250:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8251:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8252:          /* 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  8253:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8254:          /* for (j=2; j<= nlstate ; j ++) */
                   8255:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8256:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8257:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8258:        } /* nlstate */
1.264     brouard  8259:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8260:       } /* end cpt state*/ 
                   8261:     } /* end covariate */  
1.296     brouard  8262:   } /* End if prevbcast */
1.218     brouard  8263:   
1.223     brouard  8264:   /* 8eme */
1.218     brouard  8265:   if(prevfcast==1){
1.288     brouard  8266:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8267:     
1.237     brouard  8268:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8269:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8270:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8271:        continue;
1.211     brouard  8272:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8273:        strcpy(gplotlabel,"(");      
1.288     brouard  8274:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8275:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8276:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8277:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8278:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8279:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8280:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8281:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8282:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8283:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8284:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8285:        }
1.237     brouard  8286:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8287:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8288:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8289:        }       
1.264     brouard  8290:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8291:        fprintf(ficgp,"\n#\n");
                   8292:        if(invalidvarcomb[k1]){
                   8293:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8294:          continue;
                   8295:        }
                   8296:        
                   8297:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8298:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8299:        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  8300:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8301: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8302: 
                   8303:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8304:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8305:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8306:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8307:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8308:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8309:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8310:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8311:          if(i==istart){
1.227     brouard  8312:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8313:          }else{
                   8314:            fprintf(ficgp,",\\\n '' ");
                   8315:          }
                   8316:          if(cptcoveff ==0){ /* No covariate */
                   8317:            ioffset=2; /* Age is in 2 */
                   8318:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8319:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8320:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8321:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8322:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8323:            if(i==nlstate+1){
1.270     brouard  8324:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8325:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8326:              fprintf(ficgp,",\\\n '' ");
                   8327:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8328:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8329:                     offyear,                           \
1.268     brouard  8330:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8331:            }else
1.227     brouard  8332:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8333:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8334:          }else{ /* more than 2 covariates */
1.270     brouard  8335:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8336:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8337:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8338:            iyearc=ioffset-1;
                   8339:            iagec=ioffset;
1.227     brouard  8340:            fprintf(ficgp," u %d:(",ioffset); 
                   8341:            kl=0;
                   8342:            strcpy(gplotcondition,"(");
                   8343:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8344:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8345:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8346:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8347:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8348:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8349:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8350:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8351:              kl++;
                   8352:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8353:              kl++;
                   8354:              if(k <cptcoveff && cptcoveff>1)
                   8355:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8356:            }
                   8357:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8358:            /* 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 *\/ */
                   8359:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8360:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8361:            /* ''  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*/
                   8362:            if(i==nlstate+1){
1.270     brouard  8363:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8364:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8365:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8366:              fprintf(ficgp," u %d:(",iagec); 
                   8367:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8368:                      iyearc, iagec, offyear,                           \
                   8369:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8370: /*  '' 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  8371:            }else{
                   8372:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8373:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8374:            }
                   8375:          } /* end if covariate */
                   8376:        } /* nlstate */
1.264     brouard  8377:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8378:       } /* end cpt state*/
                   8379:     } /* end covariate */
                   8380:   } /* End if prevfcast */
1.227     brouard  8381:   
1.296     brouard  8382:   if(prevbcast==1){
1.268     brouard  8383:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8384:     
                   8385:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8386:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8387:       if(m != 1 && TKresult[nres]!= k1)
                   8388:        continue;
                   8389:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8390:        strcpy(gplotlabel,"(");      
                   8391:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8392:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8393:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8394:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8395:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8396:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8397:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8398:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8399:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8400:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8401:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8402:        }
                   8403:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8404:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8405:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.268     brouard  8406:        }       
                   8407:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8408:        fprintf(ficgp,"\n#\n");
                   8409:        if(invalidvarcomb[k1]){
                   8410:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8411:          continue;
                   8412:        }
                   8413:        
                   8414:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8415:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8416:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8417:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8418: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8419: 
                   8420:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8421:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8422:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8423:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8424:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8425:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8426:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8427:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8428:          if(i==istart){
                   8429:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8430:          }else{
                   8431:            fprintf(ficgp,",\\\n '' ");
                   8432:          }
                   8433:          if(cptcoveff ==0){ /* No covariate */
                   8434:            ioffset=2; /* Age is in 2 */
                   8435:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8436:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8437:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8438:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8439:            fprintf(ficgp," u %d:(", ioffset); 
                   8440:            if(i==nlstate+1){
1.270     brouard  8441:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8442:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8443:              fprintf(ficgp,",\\\n '' ");
                   8444:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8445:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8446:                     offbyear,                          \
                   8447:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8448:            }else
                   8449:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8450:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8451:          }else{ /* more than 2 covariates */
1.270     brouard  8452:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8453:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8454:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8455:            iyearc=ioffset-1;
                   8456:            iagec=ioffset;
1.268     brouard  8457:            fprintf(ficgp," u %d:(",ioffset); 
                   8458:            kl=0;
                   8459:            strcpy(gplotcondition,"(");
                   8460:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8461:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8462:              lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8463:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8464:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8465:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8466:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8467:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8468:              kl++;
                   8469:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8470:              kl++;
                   8471:              if(k <cptcoveff && cptcoveff>1)
                   8472:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8473:            }
                   8474:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8475:            /* 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 *\/ */
                   8476:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8477:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8478:            /* ''  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*/
                   8479:            if(i==nlstate+1){
1.270     brouard  8480:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8481:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8482:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8483:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8484:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8485:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8486:                      iyearc,iagec,offbyear,                            \
                   8487:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8488: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8489:            }else{
                   8490:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8491:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8492:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8493:            }
                   8494:          } /* end if covariate */
                   8495:        } /* nlstate */
                   8496:        fprintf(ficgp,"\nset out; unset label;\n");
                   8497:       } /* end cpt state*/
                   8498:     } /* end covariate */
1.296     brouard  8499:   } /* End if prevbcast */
1.268     brouard  8500:   
1.227     brouard  8501:   
1.238     brouard  8502:   /* 9eme writing MLE parameters */
                   8503:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8504:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8505:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8506:     for(k=1; k <=(nlstate+ndeath); k++){
                   8507:       if (k != i) {
1.227     brouard  8508:        fprintf(ficgp,"#   current state %d\n",k);
                   8509:        for(j=1; j <=ncovmodel; j++){
                   8510:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8511:          jk++; 
                   8512:        }
                   8513:        fprintf(ficgp,"\n");
1.126     brouard  8514:       }
                   8515:     }
1.223     brouard  8516:   }
1.187     brouard  8517:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8518:   
1.145     brouard  8519:   /*goto avoid;*/
1.238     brouard  8520:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8521:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8522:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8523:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8524:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8525:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8526:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8527:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8528:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8529:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8530:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8531:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8532:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8533:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8534:   fprintf(ficgp,"#\n");
1.223     brouard  8535:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8536:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8537:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8538:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8539:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8540:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8541:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8542:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8543:        continue;
1.264     brouard  8544:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8545:       strcpy(gplotlabel,"(");
1.276     brouard  8546:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8547:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8548:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8549:        lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.264     brouard  8550:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8551:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8552:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8553:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8554:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.264     brouard  8555:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8556:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8557:       }
1.237     brouard  8558:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8559:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8560:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8561:       }        
1.264     brouard  8562:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8563:       fprintf(ficgp,"\n#\n");
1.264     brouard  8564:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8565:       fprintf(ficgp,"\nset key outside ");
                   8566:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8567:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8568:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8569:       if (ng==1){
                   8570:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8571:        fprintf(ficgp,"\nunset log y");
                   8572:       }else if (ng==2){
                   8573:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8574:        fprintf(ficgp,"\nset log y");
                   8575:       }else if (ng==3){
                   8576:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8577:        fprintf(ficgp,"\nset log y");
                   8578:       }else
                   8579:        fprintf(ficgp,"\nunset title ");
                   8580:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8581:       i=1;
                   8582:       for(k2=1; k2<=nlstate; k2++) {
                   8583:        k3=i;
                   8584:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8585:          if (k != k2){
                   8586:            switch( ng) {
                   8587:            case 1:
                   8588:              if(nagesqr==0)
                   8589:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8590:              else /* nagesqr =1 */
                   8591:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8592:              break;
                   8593:            case 2: /* ng=2 */
                   8594:              if(nagesqr==0)
                   8595:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8596:              else /* nagesqr =1 */
                   8597:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8598:              break;
                   8599:            case 3:
                   8600:              if(nagesqr==0)
                   8601:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8602:              else /* nagesqr =1 */
                   8603:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8604:              break;
                   8605:            }
                   8606:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8607:            ijp=1; /* product no age */
                   8608:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8609:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8610:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8611:              switch(Typevar[j]){
                   8612:              case 1:
                   8613:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8614:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8615:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8616:                      if(DummyV[j]==0){/* Bug valgrind */
                   8617:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8618:                      }else{ /* quantitative */
                   8619:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8620:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8621:                      }
                   8622:                      ij++;
1.268     brouard  8623:                    }
1.237     brouard  8624:                  }
1.329     brouard  8625:                }
                   8626:                break;
                   8627:              case 2:
                   8628:                if(cptcovprod >0){
                   8629:                  if(j==Tprod[ijp]) { /* */ 
                   8630:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8631:                    if(ijp <=cptcovprod) { /* Product */
                   8632:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8633:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8634:                          /* 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)]); */
                   8635:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8636:                        }else{ /* Vn is dummy and Vm is quanti */
                   8637:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8638:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8639:                        }
                   8640:                      }else{ /* Vn*Vm Vn is quanti */
                   8641:                        if(DummyV[Tvard[ijp][2]]==0){
                   8642:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8643:                        }else{ /* Both quanti */
                   8644:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8645:                        }
1.268     brouard  8646:                      }
1.329     brouard  8647:                      ijp++;
1.237     brouard  8648:                    }
1.329     brouard  8649:                  } /* end Tprod */
                   8650:                }
                   8651:                break;
                   8652:              case 0:
                   8653:                /* simple covariate */
1.264     brouard  8654:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8655:                if(Dummy[j]==0){
                   8656:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8657:                }else{ /* quantitative */
                   8658:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8659:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8660:                }
1.329     brouard  8661:               /* end simple */
                   8662:                break;
                   8663:              default:
                   8664:                break;
                   8665:              } /* end switch */
1.237     brouard  8666:            } /* end j */
1.329     brouard  8667:          }else{ /* k=k2 */
                   8668:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8669:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8670:            }else
                   8671:              i=i-ncovmodel;
1.223     brouard  8672:          }
1.227     brouard  8673:          
1.223     brouard  8674:          if(ng != 1){
                   8675:            fprintf(ficgp,")/(1");
1.227     brouard  8676:            
1.264     brouard  8677:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8678:              if(nagesqr==0)
1.264     brouard  8679:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8680:              else /* nagesqr =1 */
1.264     brouard  8681:                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  8682:               
1.223     brouard  8683:              ij=1;
1.329     brouard  8684:              ijp=1;
                   8685:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8686:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8687:                switch(Typevar[j]){
                   8688:                case 1:
                   8689:                  if(cptcovage >0){ 
                   8690:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8691:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8692:                        if(DummyV[j]==0){/* Bug valgrind */
                   8693:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8694:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8695:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8696:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8697:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8698:                        }else{ /* quantitative */
                   8699:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8700:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8701:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8702:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8703:                        }
                   8704:                        ij++;
                   8705:                      }
                   8706:                    }
                   8707:                  }
                   8708:                  break;
                   8709:                case 2:
                   8710:                  if(cptcovprod >0){
                   8711:                    if(j==Tprod[ijp]) { /* */ 
                   8712:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8713:                      if(ijp <=cptcovprod) { /* Product */
                   8714:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8715:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8716:                            /* 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)]); */
                   8717:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8718:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8719:                          }else{ /* Vn is dummy and Vm is quanti */
                   8720:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8721:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8722:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8723:                          }
                   8724:                        }else{ /* Vn*Vm Vn is quanti */
                   8725:                          if(DummyV[Tvard[ijp][2]]==0){
                   8726:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8727:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8728:                          }else{ /* Both quanti */
                   8729:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8730:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8731:                          } 
                   8732:                        }
                   8733:                        ijp++;
                   8734:                      }
                   8735:                    } /* end Tprod */
                   8736:                  } /* end if */
                   8737:                  break;
                   8738:                case 0: 
                   8739:                  /* simple covariate */
                   8740:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8741:                  if(Dummy[j]==0){
                   8742:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8743:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8744:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8745:                  }else{ /* quantitative */
                   8746:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8747:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8748:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8749:                  }
                   8750:                  /* end simple */
                   8751:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8752:                  break;
                   8753:                default:
                   8754:                  break;
                   8755:                } /* end switch */
1.223     brouard  8756:              }
                   8757:              fprintf(ficgp,")");
                   8758:            }
                   8759:            fprintf(ficgp,")");
                   8760:            if(ng ==2)
1.276     brouard  8761:              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  8762:            else /* ng= 3 */
1.276     brouard  8763:              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  8764:           }else{ /* end ng <> 1 */
1.223     brouard  8765:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8766:              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  8767:          }
                   8768:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8769:            fprintf(ficgp,",");
                   8770:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8771:            fprintf(ficgp,",");
                   8772:          i=i+ncovmodel;
                   8773:        } /* end k */
                   8774:       } /* end k2 */
1.276     brouard  8775:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8776:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8777:     } /* end k1 */
1.223     brouard  8778:   } /* end ng */
                   8779:   /* avoid: */
                   8780:   fflush(ficgp); 
1.126     brouard  8781: }  /* end gnuplot */
                   8782: 
                   8783: 
                   8784: /*************** Moving average **************/
1.219     brouard  8785: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8786:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8787:    
1.222     brouard  8788:    int i, cpt, cptcod;
                   8789:    int modcovmax =1;
                   8790:    int mobilavrange, mob;
                   8791:    int iage=0;
1.288     brouard  8792:    int firstA1=0, firstA2=0;
1.222     brouard  8793: 
1.266     brouard  8794:    double sum=0., sumr=0.;
1.222     brouard  8795:    double age;
1.266     brouard  8796:    double *sumnewp, *sumnewm, *sumnewmr;
                   8797:    double *agemingood, *agemaxgood; 
                   8798:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8799:   
                   8800:   
1.278     brouard  8801:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8802:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8803: 
                   8804:    sumnewp = vector(1,ncovcombmax);
                   8805:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8806:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8807:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8808:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8809:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8810:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8811: 
                   8812:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8813:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8814:      sumnewp[cptcod]=0.;
1.266     brouard  8815:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8816:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8817:    }
                   8818:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8819:   
1.266     brouard  8820:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8821:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8822:      else mobilavrange=mobilav;
                   8823:      for (age=bage; age<=fage; age++)
                   8824:        for (i=1; i<=nlstate;i++)
                   8825:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8826:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8827:      /* We keep the original values on the extreme ages bage, fage and for 
                   8828:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8829:        we use a 5 terms etc. until the borders are no more concerned. 
                   8830:      */ 
                   8831:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8832:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8833:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8834:           sumnewm[cptcod]=0.;
                   8835:           for (i=1; i<=nlstate;i++){
1.222     brouard  8836:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8837:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8838:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8839:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8840:             }
                   8841:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8842:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8843:           } /* end i */
                   8844:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8845:         } /* end cptcod */
1.222     brouard  8846:        }/* end age */
                   8847:      }/* end mob */
1.266     brouard  8848:    }else{
                   8849:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8850:      return -1;
1.266     brouard  8851:    }
                   8852: 
                   8853:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8854:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8855:      if(invalidvarcomb[cptcod]){
                   8856:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8857:        continue;
                   8858:      }
1.219     brouard  8859: 
1.266     brouard  8860:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8861:        sumnewm[cptcod]=0.;
                   8862:        sumnewmr[cptcod]=0.;
                   8863:        for (i=1; i<=nlstate;i++){
                   8864:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8865:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8866:        }
                   8867:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8868:         agemingoodr[cptcod]=age;
                   8869:        }
                   8870:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8871:           agemingood[cptcod]=age;
                   8872:        }
                   8873:      } /* age */
                   8874:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8875:        sumnewm[cptcod]=0.;
1.266     brouard  8876:        sumnewmr[cptcod]=0.;
1.222     brouard  8877:        for (i=1; i<=nlstate;i++){
                   8878:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8879:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8880:        }
                   8881:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8882:         agemaxgoodr[cptcod]=age;
1.222     brouard  8883:        }
                   8884:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8885:         agemaxgood[cptcod]=age;
                   8886:        }
                   8887:      } /* age */
                   8888:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8889:      /* but they will change */
1.288     brouard  8890:      firstA1=0;firstA2=0;
1.266     brouard  8891:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8892:        sumnewm[cptcod]=0.;
                   8893:        sumnewmr[cptcod]=0.;
                   8894:        for (i=1; i<=nlstate;i++){
                   8895:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8896:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8897:        }
                   8898:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8899:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8900:           agemaxgoodr[cptcod]=age;  /* age min */
                   8901:           for (i=1; i<=nlstate;i++)
                   8902:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8903:         }else{ /* bad we change the value with the values of good ages */
                   8904:           for (i=1; i<=nlstate;i++){
                   8905:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8906:           } /* i */
                   8907:         } /* end bad */
                   8908:        }else{
                   8909:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8910:           agemaxgood[cptcod]=age;
                   8911:         }else{ /* bad we change the value with the values of good ages */
                   8912:           for (i=1; i<=nlstate;i++){
                   8913:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8914:           } /* i */
                   8915:         } /* end bad */
                   8916:        }/* end else */
                   8917:        sum=0.;sumr=0.;
                   8918:        for (i=1; i<=nlstate;i++){
                   8919:         sum+=mobaverage[(int)age][i][cptcod];
                   8920:         sumr+=probs[(int)age][i][cptcod];
                   8921:        }
                   8922:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8923:         if(!firstA1){
                   8924:           firstA1=1;
                   8925:           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);
                   8926:         }
                   8927:         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  8928:        } /* end bad */
                   8929:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8930:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8931:         if(!firstA2){
                   8932:           firstA2=1;
                   8933:           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);
                   8934:         }
                   8935:         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  8936:        } /* end bad */
                   8937:      }/* age */
1.266     brouard  8938: 
                   8939:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8940:        sumnewm[cptcod]=0.;
1.266     brouard  8941:        sumnewmr[cptcod]=0.;
1.222     brouard  8942:        for (i=1; i<=nlstate;i++){
                   8943:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8944:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8945:        } 
                   8946:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8947:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8948:           agemingoodr[cptcod]=age;
                   8949:           for (i=1; i<=nlstate;i++)
                   8950:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8951:         }else{ /* bad we change the value with the values of good ages */
                   8952:           for (i=1; i<=nlstate;i++){
                   8953:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8954:           } /* i */
                   8955:         } /* end bad */
                   8956:        }else{
                   8957:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8958:           agemingood[cptcod]=age;
                   8959:         }else{ /* bad */
                   8960:           for (i=1; i<=nlstate;i++){
                   8961:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8962:           } /* i */
                   8963:         } /* end bad */
                   8964:        }/* end else */
                   8965:        sum=0.;sumr=0.;
                   8966:        for (i=1; i<=nlstate;i++){
                   8967:         sum+=mobaverage[(int)age][i][cptcod];
                   8968:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8969:        }
1.266     brouard  8970:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8971:         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  8972:        } /* end bad */
                   8973:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8974:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8975:         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  8976:        } /* end bad */
                   8977:      }/* age */
1.266     brouard  8978: 
1.222     brouard  8979:                
                   8980:      for (age=bage; age<=fage; age++){
1.235     brouard  8981:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8982:        sumnewp[cptcod]=0.;
                   8983:        sumnewm[cptcod]=0.;
                   8984:        for (i=1; i<=nlstate;i++){
                   8985:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8986:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8987:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8988:        }
                   8989:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8990:      }
                   8991:      /* printf("\n"); */
                   8992:      /* } */
1.266     brouard  8993: 
1.222     brouard  8994:      /* brutal averaging */
1.266     brouard  8995:      /* for (i=1; i<=nlstate;i++){ */
                   8996:      /*   for (age=1; age<=bage; age++){ */
                   8997:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8998:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8999:      /*   }     */
                   9000:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9001:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9002:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9003:      /*   } */
                   9004:      /* } /\* end i status *\/ */
                   9005:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9006:      /*   for (age=1; age<=AGESUP; age++){ */
                   9007:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9008:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9009:      /*   } */
                   9010:      /* } */
1.222     brouard  9011:    }/* end cptcod */
1.266     brouard  9012:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9013:    free_vector(agemaxgood,1, ncovcombmax);
                   9014:    free_vector(agemingood,1, ncovcombmax);
                   9015:    free_vector(agemingoodr,1, ncovcombmax);
                   9016:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9017:    free_vector(sumnewm,1, ncovcombmax);
                   9018:    free_vector(sumnewp,1, ncovcombmax);
                   9019:    return 0;
                   9020:  }/* End movingaverage */
1.218     brouard  9021:  
1.126     brouard  9022: 
1.296     brouard  9023:  
1.126     brouard  9024: /************** Forecasting ******************/
1.296     brouard  9025: /* 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)*/
                   9026: 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){
                   9027:   /* dateintemean, mean date of interviews
                   9028:      dateprojd, year, month, day of starting projection 
                   9029:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9030:      agemin, agemax range of age
                   9031:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9032:   */
1.296     brouard  9033:   /* double anprojd, mprojd, jprojd; */
                   9034:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9035:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9036:   double agec; /* generic age */
1.296     brouard  9037:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9038:   double *popeffectif,*popcount;
                   9039:   double ***p3mat;
1.218     brouard  9040:   /* double ***mobaverage; */
1.126     brouard  9041:   char fileresf[FILENAMELENGTH];
                   9042: 
                   9043:   agelim=AGESUP;
1.211     brouard  9044:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9045:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9046:      We still use firstpass and lastpass as another selection.
                   9047:   */
1.214     brouard  9048:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9049:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9050:  
1.201     brouard  9051:   strcpy(fileresf,"F_"); 
                   9052:   strcat(fileresf,fileresu);
1.126     brouard  9053:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9054:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9055:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9056:   }
1.235     brouard  9057:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9058:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9059: 
1.225     brouard  9060:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9061: 
                   9062: 
                   9063:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9064:   if (stepm<=12) stepsize=1;
                   9065:   if(estepm < stepm){
                   9066:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9067:   }
1.270     brouard  9068:   else{
                   9069:     hstepm=estepm;   
                   9070:   }
                   9071:   if(estepm > stepm){ /* Yes every two year */
                   9072:     stepsize=2;
                   9073:   }
1.296     brouard  9074:   hstepm=hstepm/stepm;
1.126     brouard  9075: 
1.296     brouard  9076:   
                   9077:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9078:   /*                              fractional in yp1 *\/ */
                   9079:   /* aintmean=yp; */
                   9080:   /* yp2=modf((yp1*12),&yp); */
                   9081:   /* mintmean=yp; */
                   9082:   /* yp1=modf((yp2*30.5),&yp); */
                   9083:   /* jintmean=yp; */
                   9084:   /* if(jintmean==0) jintmean=1; */
                   9085:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9086: 
1.296     brouard  9087: 
                   9088:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9089:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9090:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9091:   i1=pow(2,cptcoveff);
1.126     brouard  9092:   if (cptcovn < 1){i1=1;}
                   9093:   
1.296     brouard  9094:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9095:   
                   9096:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9097:   
1.126     brouard  9098: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9099:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9100:     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  9101:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9102:       continue;
1.227     brouard  9103:     if(invalidvarcomb[k]){
                   9104:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9105:       continue;
                   9106:     }
                   9107:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9108:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9109:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9110:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9111:     }
1.235     brouard  9112:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9113:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9114:     }
1.227     brouard  9115:     fprintf(ficresf," yearproj age");
                   9116:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9117:       for(i=1; i<=nlstate;i++)               
                   9118:        fprintf(ficresf," p%d%d",i,j);
                   9119:       fprintf(ficresf," wp.%d",j);
                   9120:     }
1.296     brouard  9121:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9122:       fprintf(ficresf,"\n");
1.296     brouard  9123:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9124:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9125:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9126:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9127:        nhstepm = nhstepm/hstepm; 
                   9128:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9129:        oldm=oldms;savm=savms;
1.268     brouard  9130:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9131:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9132:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9133:        for (h=0; h<=nhstepm; h++){
                   9134:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9135:            break;
                   9136:          }
                   9137:        }
                   9138:        fprintf(ficresf,"\n");
                   9139:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9140:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9141:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9142:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9143:        
                   9144:        for(j=1; j<=nlstate+ndeath;j++) {
                   9145:          ppij=0.;
                   9146:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9147:            if (mobilav>=1)
                   9148:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9149:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9150:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9151:            }
1.268     brouard  9152:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9153:          } /* end i */
                   9154:          fprintf(ficresf," %.3f", ppij);
                   9155:        }/* end j */
1.227     brouard  9156:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9157:       } /* end agec */
1.266     brouard  9158:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9159:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9160:     } /* end yearp */
                   9161:   } /* end  k */
1.219     brouard  9162:        
1.126     brouard  9163:   fclose(ficresf);
1.215     brouard  9164:   printf("End of Computing forecasting \n");
                   9165:   fprintf(ficlog,"End of Computing forecasting\n");
                   9166: 
1.126     brouard  9167: }
                   9168: 
1.269     brouard  9169: /************** Back Forecasting ******************/
1.296     brouard  9170:  /* 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){ */
                   9171:  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){
                   9172:   /* back1, year, month, day of starting backprojection
1.267     brouard  9173:      agemin, agemax range of age
                   9174:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9175:      anback2 year of end of backprojection (same day and month as back1).
                   9176:      prevacurrent and prev are prevalences.
1.267     brouard  9177:   */
                   9178:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9179:   double agec; /* generic age */
1.302     brouard  9180:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9181:   double *popeffectif,*popcount;
                   9182:   double ***p3mat;
                   9183:   /* double ***mobaverage; */
                   9184:   char fileresfb[FILENAMELENGTH];
                   9185:  
1.268     brouard  9186:   agelim=AGEINF;
1.267     brouard  9187:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9188:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9189:      We still use firstpass and lastpass as another selection.
                   9190:   */
                   9191:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9192:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9193: 
                   9194:   /*Do we need to compute prevalence again?*/
                   9195: 
                   9196:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9197:   
                   9198:   strcpy(fileresfb,"FB_");
                   9199:   strcat(fileresfb,fileresu);
                   9200:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9201:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9202:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9203:   }
                   9204:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9205:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9206:   
                   9207:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9208:   
                   9209:    
                   9210:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9211:   if (stepm<=12) stepsize=1;
                   9212:   if(estepm < stepm){
                   9213:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9214:   }
1.270     brouard  9215:   else{
                   9216:     hstepm=estepm;   
                   9217:   }
                   9218:   if(estepm >= stepm){ /* Yes every two year */
                   9219:     stepsize=2;
                   9220:   }
1.267     brouard  9221:   
                   9222:   hstepm=hstepm/stepm;
1.296     brouard  9223:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9224:   /*                              fractional in yp1 *\/ */
                   9225:   /* aintmean=yp; */
                   9226:   /* yp2=modf((yp1*12),&yp); */
                   9227:   /* mintmean=yp; */
                   9228:   /* yp1=modf((yp2*30.5),&yp); */
                   9229:   /* jintmean=yp; */
                   9230:   /* if(jintmean==0) jintmean=1; */
                   9231:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9232:   
                   9233:   i1=pow(2,cptcoveff);
                   9234:   if (cptcovn < 1){i1=1;}
                   9235:   
1.296     brouard  9236:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9237:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9238:   
                   9239:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9240:   
                   9241:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9242:   for(k=1; k<=i1;k++){
                   9243:     if(i1 != 1 && TKresult[nres]!= k)
                   9244:       continue;
                   9245:     if(invalidvarcomb[k]){
                   9246:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9247:       continue;
                   9248:     }
1.268     brouard  9249:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9250:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9251:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9252:     }
                   9253:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9254:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9255:     }
                   9256:     fprintf(ficresfb," yearbproj age");
                   9257:     for(j=1; j<=nlstate+ndeath;j++){
                   9258:       for(i=1; i<=nlstate;i++)
1.268     brouard  9259:        fprintf(ficresfb," b%d%d",i,j);
                   9260:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9261:     }
1.296     brouard  9262:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9263:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9264:       fprintf(ficresfb,"\n");
1.296     brouard  9265:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9266:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9267:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9268:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9269:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9270:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9271:        nhstepm = nhstepm/hstepm;
                   9272:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9273:        oldm=oldms;savm=savms;
1.268     brouard  9274:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9275:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9276:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9277:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9278:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9279:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9280:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9281:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9282:            break;
                   9283:          }
                   9284:        }
                   9285:        fprintf(ficresfb,"\n");
                   9286:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9287:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9288:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9289:        for(i=1; i<=nlstate+ndeath;i++) {
                   9290:          ppij=0.;ppi=0.;
                   9291:          for(j=1; j<=nlstate;j++) {
                   9292:            /* if (mobilav==1) */
1.269     brouard  9293:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9294:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9295:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9296:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9297:              /* else { */
                   9298:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9299:              /* } */
1.268     brouard  9300:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9301:          } /* end j */
                   9302:          if(ppi <0.99){
                   9303:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9304:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9305:          }
                   9306:          fprintf(ficresfb," %.3f", ppij);
                   9307:        }/* end j */
1.267     brouard  9308:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9309:       } /* end agec */
                   9310:     } /* end yearp */
                   9311:   } /* end k */
1.217     brouard  9312:   
1.267     brouard  9313:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9314:   
1.267     brouard  9315:   fclose(ficresfb);
                   9316:   printf("End of Computing Back forecasting \n");
                   9317:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9318:        
1.267     brouard  9319: }
1.217     brouard  9320: 
1.269     brouard  9321: /* Variance of prevalence limit: varprlim */
                   9322:  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  9323:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9324:  
                   9325:    char fileresvpl[FILENAMELENGTH];  
                   9326:    FILE *ficresvpl;
                   9327:    double **oldm, **savm;
                   9328:    double **varpl; /* Variances of prevalence limits by age */   
                   9329:    int i1, k, nres, j ;
                   9330:    
                   9331:     strcpy(fileresvpl,"VPL_");
                   9332:     strcat(fileresvpl,fileresu);
                   9333:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9334:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9335:       exit(0);
                   9336:     }
1.288     brouard  9337:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9338:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9339:     
                   9340:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9341:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9342:     
                   9343:     i1=pow(2,cptcoveff);
                   9344:     if (cptcovn < 1){i1=1;}
                   9345: 
                   9346:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9347:       for(k=1; k<=i1;k++){ /* We find the combination equivalent to result line values of dummies */
1.269     brouard  9348:       if(i1 != 1 && TKresult[nres]!= k)
                   9349:        continue;
                   9350:       fprintf(ficresvpl,"\n#****** ");
                   9351:       printf("\n#****** ");
                   9352:       fprintf(ficlog,"\n#****** ");
                   9353:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9354:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9355:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9356:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9357:       }
                   9358:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9359:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9360:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9361:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9362:       }        
                   9363:       fprintf(ficresvpl,"******\n");
                   9364:       printf("******\n");
                   9365:       fprintf(ficlog,"******\n");
                   9366:       
                   9367:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9368:       oldm=oldms;savm=savms;
                   9369:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9370:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9371:       /*}*/
                   9372:     }
                   9373:     
                   9374:     fclose(ficresvpl);
1.288     brouard  9375:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9376:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9377: 
                   9378:  }
                   9379: /* Variance of back prevalence: varbprlim */
                   9380:  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){
                   9381:       /*------- Variance of back (stable) prevalence------*/
                   9382: 
                   9383:    char fileresvbl[FILENAMELENGTH];  
                   9384:    FILE  *ficresvbl;
                   9385: 
                   9386:    double **oldm, **savm;
                   9387:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9388:    int i1, k, nres, j ;
                   9389: 
                   9390:    strcpy(fileresvbl,"VBL_");
                   9391:    strcat(fileresvbl,fileresu);
                   9392:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9393:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9394:      exit(0);
                   9395:    }
                   9396:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9397:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9398:    
                   9399:    
                   9400:    i1=pow(2,cptcoveff);
                   9401:    if (cptcovn < 1){i1=1;}
                   9402:    
                   9403:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9404:      for(k=1; k<=i1;k++){
                   9405:        if(i1 != 1 && TKresult[nres]!= k)
                   9406:         continue;
                   9407:        fprintf(ficresvbl,"\n#****** ");
                   9408:        printf("\n#****** ");
                   9409:        fprintf(ficlog,"\n#****** ");
                   9410:        for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9411:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9412:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9413:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9414:        }
                   9415:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9416:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9417:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9418:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9419:        }
                   9420:        fprintf(ficresvbl,"******\n");
                   9421:        printf("******\n");
                   9422:        fprintf(ficlog,"******\n");
                   9423:        
                   9424:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9425:        oldm=oldms;savm=savms;
                   9426:        
                   9427:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9428:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9429:        /*}*/
                   9430:      }
                   9431:    
                   9432:    fclose(ficresvbl);
                   9433:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9434:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9435: 
                   9436:  } /* End of varbprlim */
                   9437: 
1.126     brouard  9438: /************** Forecasting *****not tested NB*************/
1.227     brouard  9439: /* 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  9440:   
1.227     brouard  9441: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9442: /*   int *popage; */
                   9443: /*   double calagedatem, agelim, kk1, kk2; */
                   9444: /*   double *popeffectif,*popcount; */
                   9445: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9446: /*   /\* double ***mobaverage; *\/ */
                   9447: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9448: 
1.227     brouard  9449: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9450: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9451: /*   agelim=AGESUP; */
                   9452: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9453:   
1.227     brouard  9454: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9455:   
                   9456:   
1.227     brouard  9457: /*   strcpy(filerespop,"POP_");  */
                   9458: /*   strcat(filerespop,fileresu); */
                   9459: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9460: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9461: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9462: /*   } */
                   9463: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9464: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9465: 
1.227     brouard  9466: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9467: 
1.227     brouard  9468: /*   /\* if (mobilav!=0) { *\/ */
                   9469: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9470: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9471: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9472: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9473: /*   /\*   } *\/ */
                   9474: /*   /\* } *\/ */
1.126     brouard  9475: 
1.227     brouard  9476: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9477: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9478:   
1.227     brouard  9479: /*   agelim=AGESUP; */
1.126     brouard  9480:   
1.227     brouard  9481: /*   hstepm=1; */
                   9482: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9483:        
1.227     brouard  9484: /*   if (popforecast==1) { */
                   9485: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9486: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9487: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9488: /*     }  */
                   9489: /*     popage=ivector(0,AGESUP); */
                   9490: /*     popeffectif=vector(0,AGESUP); */
                   9491: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9492:     
1.227     brouard  9493: /*     i=1;    */
                   9494: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9495:     
1.227     brouard  9496: /*     imx=i; */
                   9497: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9498: /*   } */
1.218     brouard  9499:   
1.227     brouard  9500: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9501: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9502: /*       k=k+1; */
                   9503: /*       fprintf(ficrespop,"\n#******"); */
                   9504: /*       for(j=1;j<=cptcoveff;j++) { */
                   9505: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9506: /*       } */
                   9507: /*       fprintf(ficrespop,"******\n"); */
                   9508: /*       fprintf(ficrespop,"# Age"); */
                   9509: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9510: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9511:       
1.227     brouard  9512: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9513: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9514:        
1.227     brouard  9515: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9516: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9517: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9518:          
1.227     brouard  9519: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9520: /*       oldm=oldms;savm=savms; */
                   9521: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9522:          
1.227     brouard  9523: /*       for (h=0; h<=nhstepm; h++){ */
                   9524: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9525: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9526: /*         }  */
                   9527: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9528: /*           kk1=0.;kk2=0; */
                   9529: /*           for(i=1; i<=nlstate;i++) {               */
                   9530: /*             if (mobilav==1)  */
                   9531: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9532: /*             else { */
                   9533: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9534: /*             } */
                   9535: /*           } */
                   9536: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9537: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9538: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9539: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9540: /*           } */
                   9541: /*         } */
                   9542: /*         for(i=1; i<=nlstate;i++){ */
                   9543: /*           kk1=0.; */
                   9544: /*           for(j=1; j<=nlstate;j++){ */
                   9545: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9546: /*           } */
                   9547: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9548: /*         } */
1.218     brouard  9549:            
1.227     brouard  9550: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9551: /*           for(j=1; j<=nlstate;j++)  */
                   9552: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9553: /*       } */
                   9554: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9555: /*     } */
                   9556: /*       } */
1.218     brouard  9557:       
1.227     brouard  9558: /*       /\******\/ */
1.218     brouard  9559:       
1.227     brouard  9560: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9561: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9562: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9563: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9564: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9565:          
1.227     brouard  9566: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9567: /*       oldm=oldms;savm=savms; */
                   9568: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9569: /*       for (h=0; h<=nhstepm; h++){ */
                   9570: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9571: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9572: /*         }  */
                   9573: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9574: /*           kk1=0.;kk2=0; */
                   9575: /*           for(i=1; i<=nlstate;i++) {               */
                   9576: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9577: /*           } */
                   9578: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9579: /*         } */
                   9580: /*       } */
                   9581: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9582: /*     } */
                   9583: /*       } */
                   9584: /*     }  */
                   9585: /*   } */
1.218     brouard  9586:   
1.227     brouard  9587: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9588:   
1.227     brouard  9589: /*   if (popforecast==1) { */
                   9590: /*     free_ivector(popage,0,AGESUP); */
                   9591: /*     free_vector(popeffectif,0,AGESUP); */
                   9592: /*     free_vector(popcount,0,AGESUP); */
                   9593: /*   } */
                   9594: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9595: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9596: /*   fclose(ficrespop); */
                   9597: /* } /\* End of popforecast *\/ */
1.218     brouard  9598:  
1.126     brouard  9599: int fileappend(FILE *fichier, char *optionfich)
                   9600: {
                   9601:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9602:     printf("Problem with file: %s\n", optionfich);
                   9603:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9604:     return (0);
                   9605:   }
                   9606:   fflush(fichier);
                   9607:   return (1);
                   9608: }
                   9609: 
                   9610: 
                   9611: /**************** function prwizard **********************/
                   9612: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9613: {
                   9614: 
                   9615:   /* Wizard to print covariance matrix template */
                   9616: 
1.164     brouard  9617:   char ca[32], cb[32];
                   9618:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9619:   int numlinepar;
                   9620: 
                   9621:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9622:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9623:   for(i=1; i <=nlstate; i++){
                   9624:     jj=0;
                   9625:     for(j=1; j <=nlstate+ndeath; j++){
                   9626:       if(j==i) continue;
                   9627:       jj++;
                   9628:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9629:       printf("%1d%1d",i,j);
                   9630:       fprintf(ficparo,"%1d%1d",i,j);
                   9631:       for(k=1; k<=ncovmodel;k++){
                   9632:        /*        printf(" %lf",param[i][j][k]); */
                   9633:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9634:        printf(" 0.");
                   9635:        fprintf(ficparo," 0.");
                   9636:       }
                   9637:       printf("\n");
                   9638:       fprintf(ficparo,"\n");
                   9639:     }
                   9640:   }
                   9641:   printf("# Scales (for hessian or gradient estimation)\n");
                   9642:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9643:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9644:   for(i=1; i <=nlstate; i++){
                   9645:     jj=0;
                   9646:     for(j=1; j <=nlstate+ndeath; j++){
                   9647:       if(j==i) continue;
                   9648:       jj++;
                   9649:       fprintf(ficparo,"%1d%1d",i,j);
                   9650:       printf("%1d%1d",i,j);
                   9651:       fflush(stdout);
                   9652:       for(k=1; k<=ncovmodel;k++){
                   9653:        /*      printf(" %le",delti3[i][j][k]); */
                   9654:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9655:        printf(" 0.");
                   9656:        fprintf(ficparo," 0.");
                   9657:       }
                   9658:       numlinepar++;
                   9659:       printf("\n");
                   9660:       fprintf(ficparo,"\n");
                   9661:     }
                   9662:   }
                   9663:   printf("# Covariance matrix\n");
                   9664: /* # 121 Var(a12)\n\ */
                   9665: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9666: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9667: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9668: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9669: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9670: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9671: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9672:   fflush(stdout);
                   9673:   fprintf(ficparo,"# Covariance matrix\n");
                   9674:   /* # 121 Var(a12)\n\ */
                   9675:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9676:   /* #   ...\n\ */
                   9677:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9678:   
                   9679:   for(itimes=1;itimes<=2;itimes++){
                   9680:     jj=0;
                   9681:     for(i=1; i <=nlstate; i++){
                   9682:       for(j=1; j <=nlstate+ndeath; j++){
                   9683:        if(j==i) continue;
                   9684:        for(k=1; k<=ncovmodel;k++){
                   9685:          jj++;
                   9686:          ca[0]= k+'a'-1;ca[1]='\0';
                   9687:          if(itimes==1){
                   9688:            printf("#%1d%1d%d",i,j,k);
                   9689:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9690:          }else{
                   9691:            printf("%1d%1d%d",i,j,k);
                   9692:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9693:            /*  printf(" %.5le",matcov[i][j]); */
                   9694:          }
                   9695:          ll=0;
                   9696:          for(li=1;li <=nlstate; li++){
                   9697:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9698:              if(lj==li) continue;
                   9699:              for(lk=1;lk<=ncovmodel;lk++){
                   9700:                ll++;
                   9701:                if(ll<=jj){
                   9702:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9703:                  if(ll<jj){
                   9704:                    if(itimes==1){
                   9705:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9706:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9707:                    }else{
                   9708:                      printf(" 0.");
                   9709:                      fprintf(ficparo," 0.");
                   9710:                    }
                   9711:                  }else{
                   9712:                    if(itimes==1){
                   9713:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9714:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9715:                    }else{
                   9716:                      printf(" 0.");
                   9717:                      fprintf(ficparo," 0.");
                   9718:                    }
                   9719:                  }
                   9720:                }
                   9721:              } /* end lk */
                   9722:            } /* end lj */
                   9723:          } /* end li */
                   9724:          printf("\n");
                   9725:          fprintf(ficparo,"\n");
                   9726:          numlinepar++;
                   9727:        } /* end k*/
                   9728:       } /*end j */
                   9729:     } /* end i */
                   9730:   } /* end itimes */
                   9731: 
                   9732: } /* end of prwizard */
                   9733: /******************* Gompertz Likelihood ******************************/
                   9734: double gompertz(double x[])
                   9735: { 
1.302     brouard  9736:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9737:   int i,n=0; /* n is the size of the sample */
                   9738: 
1.220     brouard  9739:   for (i=1;i<=imx ; i++) {
1.126     brouard  9740:     sump=sump+weight[i];
                   9741:     /*    sump=sump+1;*/
                   9742:     num=num+1;
                   9743:   }
1.302     brouard  9744:   L=0.0;
                   9745:   /* agegomp=AGEGOMP; */
1.126     brouard  9746:   /* for (i=0; i<=imx; i++) 
                   9747:      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]);*/
                   9748: 
1.302     brouard  9749:   for (i=1;i<=imx ; i++) {
                   9750:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9751:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9752:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9753:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9754:      * +
                   9755:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9756:      */
                   9757:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9758:        if (cens[i] == 1){
                   9759:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9760:        } else if (cens[i] == 0){
1.126     brouard  9761:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9762:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9763:       } else
                   9764:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9765:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9766:        L=L+A*weight[i];
1.126     brouard  9767:        /*      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  9768:      }
                   9769:   }
1.126     brouard  9770: 
1.302     brouard  9771:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9772:  
                   9773:   return -2*L*num/sump;
                   9774: }
                   9775: 
1.136     brouard  9776: #ifdef GSL
                   9777: /******************* Gompertz_f Likelihood ******************************/
                   9778: double gompertz_f(const gsl_vector *v, void *params)
                   9779: { 
1.302     brouard  9780:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9781:   double *x= (double *) v->data;
                   9782:   int i,n=0; /* n is the size of the sample */
                   9783: 
                   9784:   for (i=0;i<=imx-1 ; i++) {
                   9785:     sump=sump+weight[i];
                   9786:     /*    sump=sump+1;*/
                   9787:     num=num+1;
                   9788:   }
                   9789:  
                   9790:  
                   9791:   /* for (i=0; i<=imx; i++) 
                   9792:      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]);*/
                   9793:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9794:   for (i=1;i<=imx ; i++)
                   9795:     {
                   9796:       if (cens[i] == 1 && wav[i]>1)
                   9797:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9798:       
                   9799:       if (cens[i] == 0 && wav[i]>1)
                   9800:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9801:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9802:       
                   9803:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9804:       if (wav[i] > 1 ) { /* ??? */
                   9805:        LL=LL+A*weight[i];
                   9806:        /*      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]);*/
                   9807:       }
                   9808:     }
                   9809: 
                   9810:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9811:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9812:  
                   9813:   return -2*LL*num/sump;
                   9814: }
                   9815: #endif
                   9816: 
1.126     brouard  9817: /******************* Printing html file ***********/
1.201     brouard  9818: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9819:                  int lastpass, int stepm, int weightopt, char model[],\
                   9820:                  int imx,  double p[],double **matcov,double agemortsup){
                   9821:   int i,k;
                   9822: 
                   9823:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9824:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9825:   for (i=1;i<=2;i++) 
                   9826:     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  9827:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9828:   fprintf(fichtm,"</ul>");
                   9829: 
                   9830: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9831: 
                   9832:  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>");
                   9833: 
                   9834:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9835:    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]);
                   9836: 
                   9837:  
                   9838:   fflush(fichtm);
                   9839: }
                   9840: 
                   9841: /******************* Gnuplot file **************/
1.201     brouard  9842: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9843: 
                   9844:   char dirfileres[132],optfileres[132];
1.164     brouard  9845: 
1.126     brouard  9846:   int ng;
                   9847: 
                   9848: 
                   9849:   /*#ifdef windows */
                   9850:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9851:     /*#endif */
                   9852: 
                   9853: 
                   9854:   strcpy(dirfileres,optionfilefiname);
                   9855:   strcpy(optfileres,"vpl");
1.199     brouard  9856:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9857:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9858:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9859:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9860:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9861: 
                   9862: } 
                   9863: 
1.136     brouard  9864: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9865: {
1.126     brouard  9866: 
1.136     brouard  9867:   /*-------- data file ----------*/
                   9868:   FILE *fic;
                   9869:   char dummy[]="                         ";
1.240     brouard  9870:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9871:   int lstra;
1.136     brouard  9872:   int linei, month, year,iout;
1.302     brouard  9873:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9874:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9875:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9876:   char *stratrunc;
1.223     brouard  9877: 
1.240     brouard  9878:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9879:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  9880:   for(v=1;v<NCOVMAX;v++){
                   9881:     DummyV[v]=0;
                   9882:     FixedV[v]=0;
                   9883:   }
1.126     brouard  9884: 
1.240     brouard  9885:   for(v=1; v <=ncovcol;v++){
                   9886:     DummyV[v]=0;
                   9887:     FixedV[v]=0;
                   9888:   }
                   9889:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9890:     DummyV[v]=1;
                   9891:     FixedV[v]=0;
                   9892:   }
                   9893:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9894:     DummyV[v]=0;
                   9895:     FixedV[v]=1;
                   9896:   }
                   9897:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9898:     DummyV[v]=1;
                   9899:     FixedV[v]=1;
                   9900:   }
                   9901:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9902:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9903:     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]);
                   9904:   }
1.126     brouard  9905: 
1.136     brouard  9906:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9907:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9908:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9909:   }
1.126     brouard  9910: 
1.302     brouard  9911:     /* Is it a BOM UTF-8 Windows file? */
                   9912:   /* First data line */
                   9913:   linei=0;
                   9914:   while(fgets(line, MAXLINE, fic)) {
                   9915:     noffset=0;
                   9916:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9917:     {
                   9918:       noffset=noffset+3;
                   9919:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9920:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9921:       fflush(ficlog); return 1;
                   9922:     }
                   9923:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9924:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9925:     {
                   9926:       noffset=noffset+2;
1.304     brouard  9927:       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);
                   9928:       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  9929:       fflush(ficlog); return 1;
                   9930:     }
                   9931:     else if( line[0] == 0 && line[1] == 0)
                   9932:     {
                   9933:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9934:        noffset=noffset+4;
1.304     brouard  9935:        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);
                   9936:        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  9937:        fflush(ficlog); return 1;
                   9938:       }
                   9939:     } else{
                   9940:       ;/*printf(" Not a BOM file\n");*/
                   9941:     }
                   9942:         /* If line starts with a # it is a comment */
                   9943:     if (line[noffset] == '#') {
                   9944:       linei=linei+1;
                   9945:       break;
                   9946:     }else{
                   9947:       break;
                   9948:     }
                   9949:   }
                   9950:   fclose(fic);
                   9951:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9952:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9953:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9954:   }
                   9955:   /* Not a Bom file */
                   9956:   
1.136     brouard  9957:   i=1;
                   9958:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9959:     linei=linei+1;
                   9960:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9961:       if(line[j] == '\t')
                   9962:        line[j] = ' ';
                   9963:     }
                   9964:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9965:       ;
                   9966:     };
                   9967:     line[j+1]=0;  /* Trims blanks at end of line */
                   9968:     if(line[0]=='#'){
                   9969:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9970:       printf("Comment line\n%s\n",line);
                   9971:       continue;
                   9972:     }
                   9973:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9974:     strcpy(line, linetmp);
1.223     brouard  9975:     
                   9976:     /* Loops on waves */
                   9977:     for (j=maxwav;j>=1;j--){
                   9978:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9979:        cutv(stra, strb, line, ' '); 
                   9980:        if(strb[0]=='.') { /* Missing value */
                   9981:          lval=-1;
                   9982:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9983:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9984:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9985:            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);
                   9986:            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);
                   9987:            return 1;
                   9988:          }
                   9989:        }else{
                   9990:          errno=0;
                   9991:          /* what_kind_of_number(strb); */
                   9992:          dval=strtod(strb,&endptr); 
                   9993:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9994:          /* if(strb != endptr && *endptr == '\0') */
                   9995:          /*    dval=dlval; */
                   9996:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9997:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9998:            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);
                   9999:            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);
                   10000:            return 1;
                   10001:          }
                   10002:          cotqvar[j][iv][i]=dval; 
                   10003:          cotvar[j][ntv+iv][i]=dval; 
                   10004:        }
                   10005:        strcpy(line,stra);
1.223     brouard  10006:       }/* end loop ntqv */
1.225     brouard  10007:       
1.223     brouard  10008:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10009:        cutv(stra, strb, line, ' '); 
                   10010:        if(strb[0]=='.') { /* Missing value */
                   10011:          lval=-1;
                   10012:        }else{
                   10013:          errno=0;
                   10014:          lval=strtol(strb,&endptr,10); 
                   10015:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10016:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10017:            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);
                   10018:            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);
                   10019:            return 1;
                   10020:          }
                   10021:        }
                   10022:        if(lval <-1 || lval >1){
                   10023:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10024:  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  10025:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10026:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10027:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10028:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10029:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10030:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10031:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10032:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10033:  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  10034:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10035:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10036:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10037:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10038:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10039:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10040:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10041:          return 1;
                   10042:        }
                   10043:        cotvar[j][iv][i]=(double)(lval);
                   10044:        strcpy(line,stra);
1.223     brouard  10045:       }/* end loop ntv */
1.225     brouard  10046:       
1.223     brouard  10047:       /* Statuses  at wave */
1.137     brouard  10048:       cutv(stra, strb, line, ' '); 
1.223     brouard  10049:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10050:        lval=-1;
1.136     brouard  10051:       }else{
1.238     brouard  10052:        errno=0;
                   10053:        lval=strtol(strb,&endptr,10); 
                   10054:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10055:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10056:          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);
                   10057:          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);
                   10058:          return 1;
                   10059:        }
1.136     brouard  10060:       }
1.225     brouard  10061:       
1.136     brouard  10062:       s[j][i]=lval;
1.225     brouard  10063:       
1.223     brouard  10064:       /* Date of Interview */
1.136     brouard  10065:       strcpy(line,stra);
                   10066:       cutv(stra, strb,line,' ');
1.169     brouard  10067:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10068:       }
1.169     brouard  10069:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10070:        month=99;
                   10071:        year=9999;
1.136     brouard  10072:       }else{
1.225     brouard  10073:        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);
                   10074:        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);
                   10075:        return 1;
1.136     brouard  10076:       }
                   10077:       anint[j][i]= (double) year; 
1.302     brouard  10078:       mint[j][i]= (double)month;
                   10079:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10080:       /*       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]); */
                   10081:       /*       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]); */
                   10082:       /* } */
1.136     brouard  10083:       strcpy(line,stra);
1.223     brouard  10084:     } /* End loop on waves */
1.225     brouard  10085:     
1.223     brouard  10086:     /* Date of death */
1.136     brouard  10087:     cutv(stra, strb,line,' '); 
1.169     brouard  10088:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10089:     }
1.169     brouard  10090:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10091:       month=99;
                   10092:       year=9999;
                   10093:     }else{
1.141     brouard  10094:       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  10095:       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);
                   10096:       return 1;
1.136     brouard  10097:     }
                   10098:     andc[i]=(double) year; 
                   10099:     moisdc[i]=(double) month; 
                   10100:     strcpy(line,stra);
                   10101:     
1.223     brouard  10102:     /* Date of birth */
1.136     brouard  10103:     cutv(stra, strb,line,' '); 
1.169     brouard  10104:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10105:     }
1.169     brouard  10106:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10107:       month=99;
                   10108:       year=9999;
                   10109:     }else{
1.141     brouard  10110:       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);
                   10111:       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  10112:       return 1;
1.136     brouard  10113:     }
                   10114:     if (year==9999) {
1.141     brouard  10115:       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);
                   10116:       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  10117:       return 1;
                   10118:       
1.136     brouard  10119:     }
                   10120:     annais[i]=(double)(year);
1.302     brouard  10121:     moisnais[i]=(double)(month);
                   10122:     for (j=1;j<=maxwav;j++){
                   10123:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10124:        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]);
                   10125:        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]);
                   10126:       }
                   10127:     }
                   10128: 
1.136     brouard  10129:     strcpy(line,stra);
1.225     brouard  10130:     
1.223     brouard  10131:     /* Sample weight */
1.136     brouard  10132:     cutv(stra, strb,line,' '); 
                   10133:     errno=0;
                   10134:     dval=strtod(strb,&endptr); 
                   10135:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10136:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10137:       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  10138:       fflush(ficlog);
                   10139:       return 1;
                   10140:     }
                   10141:     weight[i]=dval; 
                   10142:     strcpy(line,stra);
1.225     brouard  10143:     
1.223     brouard  10144:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10145:       cutv(stra, strb, line, ' '); 
                   10146:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10147:        lval=-1;
1.311     brouard  10148:        coqvar[iv][i]=NAN; 
                   10149:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10150:       }else{
1.225     brouard  10151:        errno=0;
                   10152:        /* what_kind_of_number(strb); */
                   10153:        dval=strtod(strb,&endptr);
                   10154:        /* if(strb != endptr && *endptr == '\0') */
                   10155:        /*   dval=dlval; */
                   10156:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10157:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10158:          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);
                   10159:          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);
                   10160:          return 1;
                   10161:        }
                   10162:        coqvar[iv][i]=dval; 
1.226     brouard  10163:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10164:       }
                   10165:       strcpy(line,stra);
                   10166:     }/* end loop nqv */
1.136     brouard  10167:     
1.223     brouard  10168:     /* Covariate values */
1.136     brouard  10169:     for (j=ncovcol;j>=1;j--){
                   10170:       cutv(stra, strb,line,' '); 
1.223     brouard  10171:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10172:        lval=-1;
1.136     brouard  10173:       }else{
1.225     brouard  10174:        errno=0;
                   10175:        lval=strtol(strb,&endptr,10); 
                   10176:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10177:          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);
                   10178:          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);
                   10179:          return 1;
                   10180:        }
1.136     brouard  10181:       }
                   10182:       if(lval <-1 || lval >1){
1.225     brouard  10183:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10184:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10185:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10186:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10187:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10188:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10189:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10190:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10191:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10192:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10193:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10194:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10195:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10196:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10197:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10198:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10199:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10200:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10201:        return 1;
1.136     brouard  10202:       }
                   10203:       covar[j][i]=(double)(lval);
                   10204:       strcpy(line,stra);
                   10205:     }  
                   10206:     lstra=strlen(stra);
1.225     brouard  10207:     
1.136     brouard  10208:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10209:       stratrunc = &(stra[lstra-9]);
                   10210:       num[i]=atol(stratrunc);
                   10211:     }
                   10212:     else
                   10213:       num[i]=atol(stra);
                   10214:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10215:       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;}*/
                   10216:     
                   10217:     i=i+1;
                   10218:   } /* End loop reading  data */
1.225     brouard  10219:   
1.136     brouard  10220:   *imax=i-1; /* Number of individuals */
                   10221:   fclose(fic);
1.225     brouard  10222:   
1.136     brouard  10223:   return (0);
1.164     brouard  10224:   /* endread: */
1.225     brouard  10225:   printf("Exiting readdata: ");
                   10226:   fclose(fic);
                   10227:   return (1);
1.223     brouard  10228: }
1.126     brouard  10229: 
1.234     brouard  10230: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10231:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10232:   while (*p2 == ' ')
1.234     brouard  10233:     p2++; 
                   10234:   /* while ((*p1++ = *p2++) !=0) */
                   10235:   /*   ; */
                   10236:   /* do */
                   10237:   /*   while (*p2 == ' ') */
                   10238:   /*     p2++; */
                   10239:   /* while (*p1++ == *p2++); */
                   10240:   *stri=p2; 
1.145     brouard  10241: }
                   10242: 
1.330     brouard  10243: int decoderesult( char resultline[], int nres)
1.230     brouard  10244: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10245: {
1.235     brouard  10246:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10247:   char resultsav[MAXLINE];
1.330     brouard  10248:   /* int resultmodel[MAXLINE]; */
1.234     brouard  10249:   int modelresult[MAXLINE];
1.230     brouard  10250:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10251: 
1.234     brouard  10252:   removefirstspace(&resultline);
1.332     brouard  10253:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10254: 
1.332     brouard  10255:   strcpy(resultsav,resultline);
                   10256:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10257:   if (strlen(resultsav) >1){
                   10258:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   10259:   }
1.253     brouard  10260:   if(j == 0){ /* Resultline but no = */
                   10261:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10262:     return (0);
                   10263:   }
1.234     brouard  10264:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.332     brouard  10265:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of variables used in the model line, %s.\n",j, cptcovs, model);
                   10266:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of variables used in the model line, %s.\n",j, cptcovs, model);
                   10267:     /* return 1;*/
1.234     brouard  10268:   }
                   10269:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   10270:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10271:       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  10272:       /* 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  10273:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10274:       /* If a blank, then strc="V4=" and strd='\0' */
                   10275:       if(strc[0]=='\0'){
                   10276:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10277:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10278:        return 1;
                   10279:       }
1.234     brouard  10280:     }else
                   10281:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10282:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10283:     
1.230     brouard  10284:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10285:     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  10286:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10287:     /* cptcovsel++;     */
                   10288:     if (nbocc(stra,'=') >0)
                   10289:       strcpy(resultsav,stra); /* and analyzes it */
                   10290:   }
1.235     brouard  10291:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10292:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
1.318     brouard  10293:   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  10294:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10295:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10296:       match=0;
1.318     brouard  10297:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10298:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  10299:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10300:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10301:          break;
                   10302:        }
                   10303:       }
                   10304:       if(match == 0){
1.332     brouard  10305:        printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
                   10306:        fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=%s\n",Tvar[k1], resultline, model);
1.310     brouard  10307:        return 1;
1.234     brouard  10308:       }
1.332     brouard  10309:     }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*/
                   10310:       /* We feed resultmodel[k1]=k2; */
                   10311:       match=0;
                   10312:       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 */
                   10313:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10314:          modelresult[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 */
                   10315:          resultmodel[nres][k1]=k2; /* Added here */
                   10316:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10317:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10318:          break;
                   10319:        }
                   10320:       }
                   10321:       if(match == 0){
                   10322:        printf("Error in result line (Product with age): V%d is missing in result: %s according to model=%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.333   ! brouard  10323:        fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.332     brouard  10324:       return 1;
                   10325:       }
                   10326:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10327:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10328:       match=0;
                   10329:       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]);
                   10330:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10331:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10332:          /* modelresult[k2]=k1; */
                   10333:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10334:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10335:        }
                   10336:       }
                   10337:       if(match == 0){
                   10338:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][1], resultline, model);
1.333   ! brouard  10339:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10340:        return 1;
                   10341:       }
                   10342:       match=0;
                   10343:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10344:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10345:          /* modelresult[k2]=k1;*/
                   10346:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10347:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10348:          break;
                   10349:        }
                   10350:       }
                   10351:       if(match == 0){
                   10352:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][2], resultline, model);
1.333   ! brouard  10353:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10354:        return 1;
                   10355:       }
                   10356:     }/* End of testing */
1.333   ! brouard  10357:   }/* End loop cptcovt */
1.235     brouard  10358:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10359:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.318     brouard  10360:   for(k2=1; k2 <=j;k2++){ /* Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10361:     match=0;
1.318     brouard  10362:     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  10363:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10364:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10365:          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.234     brouard  10366:          ++match;
                   10367:        }
                   10368:       }
                   10369:     }
                   10370:     if(match == 0){
1.332     brouard  10371:       printf("Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
                   10372:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
1.310     brouard  10373:       return 1;
1.234     brouard  10374:     }else if(match > 1){
                   10375:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10376:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10377:       return 1;
1.234     brouard  10378:     }
                   10379:   }
1.235     brouard  10380:       
1.234     brouard  10381:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10382:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10383:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10384:   /* 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*/
                   10385:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10386:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10387:   /*    1 0 0 0 */
                   10388:   /*    2 1 0 0 */
                   10389:   /*    3 0 1 0 */ 
1.330     brouard  10390:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10391:   /*    5 0 0 1 */
1.330     brouard  10392:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10393:   /*    7 0 1 1 */
                   10394:   /*    8 1 1 1 */
1.237     brouard  10395:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10396:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10397:   /* V5*age V5 known which value for nres?  */
                   10398:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.330     brouard  10399:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* loop k1 on position in the model line (excluding product) */
1.331     brouard  10400:     /* k counting number of combination of single dummies in the equation model */
                   10401:     /* k4 counting single dummies in the equation model */
                   10402:     /* k4q counting single quantitatives in the equation model */
                   10403:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single */
                   10404:        /* k4+1= position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
1.332     brouard  10405:       /* 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  10406:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10407:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10408:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10409:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10410:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10411:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
                   10412:       /* Tvresult[nres][result_position]= id of the dummy variable at the result_position in the nres resultline                     */
                   10413:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10414:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10415:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10416:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10417:       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  10418:       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.332     brouard  10419:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Stores the value into the name of the variable. */
                   10420:       /* Tinvresult[nres][4]=1 */
1.330     brouard  10421:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
1.237     brouard  10422:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10423:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.332     brouard  10424:       precov[nres][k1]=Tvalsel[k3];
                   10425:       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  10426:       k4++;;
1.331     brouard  10427:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10428:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10429:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10430:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10431:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10432:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10433:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.237     brouard  10434:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10435:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   10436:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10437:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10438:       precov[nres][k1]=Tvalsel[k3q];
                   10439:       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  10440:       k4q++;;
1.331     brouard  10441:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10442:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10443:       /* Wrong we want the value of variable name Tvar[k1] */
                   10444:       
                   10445:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10446:       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)*/
                   10447:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.332     brouard  10448:       precov[nres][k1]=Tvalsel[k3];
                   10449:       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  10450:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10451:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10452:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   10453:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10454:       precov[nres][k1]=Tvalsel[k3q];
                   10455:       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  10456:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10457:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10458:       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  10459:     }else{
1.332     brouard  10460:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10461:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10462:     }
                   10463:   }
1.234     brouard  10464:   
1.235     brouard  10465:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  10466:   return (0);
                   10467: }
1.235     brouard  10468: 
1.230     brouard  10469: int decodemodel( char model[], int lastobs)
                   10470:  /**< This routine decodes the model and returns:
1.224     brouard  10471:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10472:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10473:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10474:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10475:        * - cptcovage number of covariates with age*products =2
                   10476:        * - cptcovs number of simple covariates
                   10477:        * - 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
                   10478:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10479:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10480:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10481:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10482:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10483:        */
1.319     brouard  10484: /* 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  10485: {
1.238     brouard  10486:   int i, j, k, ks, v;
1.227     brouard  10487:   int  j1, k1, k2, k3, k4;
1.136     brouard  10488:   char modelsav[80];
1.145     brouard  10489:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10490:   char *strpt;
1.136     brouard  10491: 
1.145     brouard  10492:   /*removespace(model);*/
1.136     brouard  10493:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10494:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10495:     if (strstr(model,"AGE") !=0){
1.192     brouard  10496:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10497:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10498:       return 1;
                   10499:     }
1.141     brouard  10500:     if (strstr(model,"v") !=0){
                   10501:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10502:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10503:       return 1;
                   10504:     }
1.187     brouard  10505:     strcpy(modelsav,model); 
                   10506:     if ((strpt=strstr(model,"age*age")) !=0){
                   10507:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10508:       if(strpt != model){
1.234     brouard  10509:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10510:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10511:  corresponding column of parameters.\n",model);
1.234     brouard  10512:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10513:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10514:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10515:        return 1;
1.225     brouard  10516:       }
1.187     brouard  10517:       nagesqr=1;
                   10518:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10519:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10520:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10521:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10522:       else 
1.234     brouard  10523:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10524:     }else
                   10525:       nagesqr=0;
                   10526:     if (strlen(modelsav) >1){
                   10527:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10528:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10529:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10530:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10531:                     * cst, age and age*age 
                   10532:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10533:       /* including age products which are counted in cptcovage.
                   10534:        * but the covariates which are products must be treated 
                   10535:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10536:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10537:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10538:       
                   10539:       
1.187     brouard  10540:       /*   Design
                   10541:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10542:        *  <          ncovcol=8                >
                   10543:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10544:        *   k=  1    2      3       4     5       6      7        8
                   10545:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10546:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10547:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10548:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10549:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10550:        *  Tage[++cptcovage]=k
                   10551:        *       if products, new covar are created after ncovcol with k1
                   10552:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10553:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10554:        *  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
                   10555:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10556:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10557:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10558:        *  <          ncovcol=8                >
                   10559:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10560:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10561:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10562:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10563:        * p Tprod[1]@2={                         6, 5}
                   10564:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10565:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10566:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10567:        *How to reorganize? Tvars(orted)
1.187     brouard  10568:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10569:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10570:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10571:        * Struct []
                   10572:        */
1.225     brouard  10573:       
1.187     brouard  10574:       /* This loop fills the array Tvar from the string 'model'.*/
                   10575:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10576:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10577:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10578:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10579:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10580:       /*       k=1 Tvar[1]=2 (from V2) */
                   10581:       /*       k=5 Tvar[5] */
                   10582:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10583:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10584:       /*       } */
1.198     brouard  10585:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10586:       /*
                   10587:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10588:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10589:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10590:       }
1.187     brouard  10591:       cptcovage=0;
1.319     brouard  10592:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10593:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10594:                                         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" */
                   10595:        if (nbocc(modelsav,'+')==0)
                   10596:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10597:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10598:        /*scanf("%d",i);*/
1.319     brouard  10599:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10600:          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  10601:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10602:            /* covar is not filled and then is empty */
                   10603:            cptcovprod--;
                   10604:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10605:            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  10606:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10607:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10608:            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  10609:            /*printf("stre=%s ", stre);*/
                   10610:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10611:            cptcovprod--;
                   10612:            cutl(stre,strb,strc,'V');
                   10613:            Tvar[k]=atoi(stre);
                   10614:            Typevar[k]=1;  /* 1 for age product */
                   10615:            cptcovage++;
                   10616:            Tage[cptcovage]=k;
                   10617:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10618:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10619:            cptcovn++;
                   10620:            cptcovprodnoage++;k1++;
                   10621:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10622:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10623:                                                because this model-covariate is a construction we invent a new column
                   10624:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10625:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10626:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10627:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10628:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10629:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10630:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10631:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10632:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10633:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10634:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10635:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10636:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10637:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10638:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10639:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10640:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10641:            for (i=1; i<=lastobs;i++){
                   10642:              /* Computes the new covariate which is a product of
                   10643:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10644:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10645:            }
                   10646:          } /* End age is not in the model */
                   10647:        } /* End if model includes a product */
1.319     brouard  10648:        else { /* not a product */
1.234     brouard  10649:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10650:          /*  scanf("%d",i);*/
                   10651:          cutl(strd,strc,strb,'V');
                   10652:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10653:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10654:          Tvar[k]=atoi(strd);
                   10655:          Typevar[k]=0;  /* 0 for simple covariates */
                   10656:        }
                   10657:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10658:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10659:                                  scanf("%d",i);*/
1.187     brouard  10660:       } /* end of loop + on total covariates */
                   10661:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10662:   } /* end if strlen(model == 0) */
1.136     brouard  10663:   
                   10664:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10665:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10666:   
1.136     brouard  10667:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10668:      printf("cptcovprod=%d ", cptcovprod);
                   10669:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10670:      scanf("%d ",i);*/
                   10671: 
                   10672: 
1.230     brouard  10673: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10674:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10675: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10676:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10677:    k =           1    2   3     4       5       6      7      8        9
                   10678:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10679:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10680:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10681:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10682:          Tmodelind[combination of covar]=k;
1.225     brouard  10683: */  
                   10684: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10685:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10686:   /* 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  10687:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10688:   printf("Model=1+age+%s\n\
1.227     brouard  10689: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10690: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10691: 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  10692:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10693: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10694: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10695: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
1.285     brouard  10696:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10697:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
                   10698:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10699:       Fixed[k]= 0;
                   10700:       Dummy[k]= 0;
1.225     brouard  10701:       ncoveff++;
1.232     brouard  10702:       ncovf++;
1.234     brouard  10703:       nsd++;
                   10704:       modell[k].maintype= FTYPE;
                   10705:       TvarsD[nsd]=Tvar[k];
                   10706:       TvarsDind[nsd]=k;
1.330     brouard  10707:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10708:       TvarF[ncovf]=Tvar[k];
                   10709:       TvarFind[ncovf]=k;
                   10710:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10711:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10712:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10713:       Fixed[k]= 0;
                   10714:       Dummy[k]= 0;
                   10715:       ncoveff++;
                   10716:       ncovf++;
                   10717:       modell[k].maintype= FTYPE;
                   10718:       TvarF[ncovf]=Tvar[k];
1.330     brouard  10719:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10720:       TvarFind[ncovf]=k;
1.230     brouard  10721:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10722:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10723:     }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  10724:       Fixed[k]= 0;
                   10725:       Dummy[k]= 1;
1.230     brouard  10726:       nqfveff++;
1.234     brouard  10727:       modell[k].maintype= FTYPE;
                   10728:       modell[k].subtype= FQ;
                   10729:       nsq++;
                   10730:       TvarsQ[nsq]=Tvar[k];
                   10731:       TvarsQind[nsq]=k;
1.232     brouard  10732:       ncovf++;
1.234     brouard  10733:       TvarF[ncovf]=Tvar[k];
                   10734:       TvarFind[ncovf]=k;
1.231     brouard  10735:       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  10736:       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  10737:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10738:       Fixed[k]= 1;
                   10739:       Dummy[k]= 0;
1.225     brouard  10740:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10741:       modell[k].maintype= VTYPE;
                   10742:       modell[k].subtype= VD;
                   10743:       nsd++;
                   10744:       TvarsD[nsd]=Tvar[k];
                   10745:       TvarsDind[nsd]=k;
1.330     brouard  10746:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10747:       ncovv++; /* Only simple time varying variables */
                   10748:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10749:       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  10750:       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 */
                   10751:       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  10752:       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);
                   10753:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10754:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10755:       Fixed[k]= 1;
                   10756:       Dummy[k]= 1;
                   10757:       nqtveff++;
                   10758:       modell[k].maintype= VTYPE;
                   10759:       modell[k].subtype= VQ;
                   10760:       ncovv++; /* Only simple time varying variables */
                   10761:       nsq++;
1.319     brouard  10762:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */
1.332     brouard  10763:       TvarsQind[nsq]=k; /* For single quantitative covariate gives the model position of each single quantitative covariate */
1.234     brouard  10764:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10765:       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  10766:       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 */
                   10767:       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  10768:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10769:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10770:       printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
1.228     brouard  10771:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10772:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10773:       ncova++;
                   10774:       TvarA[ncova]=Tvar[k];
                   10775:       TvarAind[ncova]=k;
1.231     brouard  10776:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10777:        Fixed[k]= 2;
                   10778:        Dummy[k]= 2;
                   10779:        modell[k].maintype= ATYPE;
                   10780:        modell[k].subtype= APFD;
                   10781:        /* ncoveff++; */
1.227     brouard  10782:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10783:        Fixed[k]= 2;
                   10784:        Dummy[k]= 3;
                   10785:        modell[k].maintype= ATYPE;
                   10786:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10787:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10788:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10789:        Fixed[k]= 3;
                   10790:        Dummy[k]= 2;
                   10791:        modell[k].maintype= ATYPE;
                   10792:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10793:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10794:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10795:        Fixed[k]= 3;
                   10796:        Dummy[k]= 3;
                   10797:        modell[k].maintype= ATYPE;
                   10798:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10799:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10800:       }
                   10801:     }else if (Typevar[k] == 2) {  /* product without age */
                   10802:       k1=Tposprod[k];
                   10803:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10804:        if(Tvard[k1][2] <=ncovcol){
                   10805:          Fixed[k]= 1;
                   10806:          Dummy[k]= 0;
                   10807:          modell[k].maintype= FTYPE;
                   10808:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10809:          ncovf++; /* Fixed variables without age */
                   10810:          TvarF[ncovf]=Tvar[k];
                   10811:          TvarFind[ncovf]=k;
                   10812:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10813:          Fixed[k]= 0;  /* or 2 ?*/
                   10814:          Dummy[k]= 1;
                   10815:          modell[k].maintype= FTYPE;
                   10816:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10817:          ncovf++; /* Varying variables without age */
                   10818:          TvarF[ncovf]=Tvar[k];
                   10819:          TvarFind[ncovf]=k;
                   10820:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10821:          Fixed[k]= 1;
                   10822:          Dummy[k]= 0;
                   10823:          modell[k].maintype= VTYPE;
                   10824:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10825:          ncovv++; /* Varying variables without age */
                   10826:          TvarV[ncovv]=Tvar[k];
                   10827:          TvarVind[ncovv]=k;
                   10828:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10829:          Fixed[k]= 1;
                   10830:          Dummy[k]= 1;
                   10831:          modell[k].maintype= VTYPE;
                   10832:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10833:          ncovv++; /* Varying variables without age */
                   10834:          TvarV[ncovv]=Tvar[k];
                   10835:          TvarVind[ncovv]=k;
                   10836:        }
1.227     brouard  10837:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10838:        if(Tvard[k1][2] <=ncovcol){
                   10839:          Fixed[k]= 0;  /* or 2 ?*/
                   10840:          Dummy[k]= 1;
                   10841:          modell[k].maintype= FTYPE;
                   10842:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10843:          ncovf++; /* Fixed variables without age */
                   10844:          TvarF[ncovf]=Tvar[k];
                   10845:          TvarFind[ncovf]=k;
                   10846:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10847:          Fixed[k]= 1;
                   10848:          Dummy[k]= 1;
                   10849:          modell[k].maintype= VTYPE;
                   10850:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10851:          ncovv++; /* Varying variables without age */
                   10852:          TvarV[ncovv]=Tvar[k];
                   10853:          TvarVind[ncovv]=k;
                   10854:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10855:          Fixed[k]= 1;
                   10856:          Dummy[k]= 1;
                   10857:          modell[k].maintype= VTYPE;
                   10858:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10859:          ncovv++; /* Varying variables without age */
                   10860:          TvarV[ncovv]=Tvar[k];
                   10861:          TvarVind[ncovv]=k;
                   10862:          ncovv++; /* Varying variables without age */
                   10863:          TvarV[ncovv]=Tvar[k];
                   10864:          TvarVind[ncovv]=k;
                   10865:        }
1.227     brouard  10866:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10867:        if(Tvard[k1][2] <=ncovcol){
                   10868:          Fixed[k]= 1;
                   10869:          Dummy[k]= 1;
                   10870:          modell[k].maintype= VTYPE;
                   10871:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10872:          ncovv++; /* Varying variables without age */
                   10873:          TvarV[ncovv]=Tvar[k];
                   10874:          TvarVind[ncovv]=k;
                   10875:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10876:          Fixed[k]= 1;
                   10877:          Dummy[k]= 1;
                   10878:          modell[k].maintype= VTYPE;
                   10879:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10880:          ncovv++; /* Varying variables without age */
                   10881:          TvarV[ncovv]=Tvar[k];
                   10882:          TvarVind[ncovv]=k;
                   10883:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10884:          Fixed[k]= 1;
                   10885:          Dummy[k]= 0;
                   10886:          modell[k].maintype= VTYPE;
                   10887:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10888:          ncovv++; /* Varying variables without age */
                   10889:          TvarV[ncovv]=Tvar[k];
                   10890:          TvarVind[ncovv]=k;
                   10891:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10892:          Fixed[k]= 1;
                   10893:          Dummy[k]= 1;
                   10894:          modell[k].maintype= VTYPE;
                   10895:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10896:          ncovv++; /* Varying variables without age */
                   10897:          TvarV[ncovv]=Tvar[k];
                   10898:          TvarVind[ncovv]=k;
                   10899:        }
1.227     brouard  10900:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10901:        if(Tvard[k1][2] <=ncovcol){
                   10902:          Fixed[k]= 1;
                   10903:          Dummy[k]= 1;
                   10904:          modell[k].maintype= VTYPE;
                   10905:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10906:          ncovv++; /* Varying variables without age */
                   10907:          TvarV[ncovv]=Tvar[k];
                   10908:          TvarVind[ncovv]=k;
                   10909:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10910:          Fixed[k]= 1;
                   10911:          Dummy[k]= 1;
                   10912:          modell[k].maintype= VTYPE;
                   10913:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10914:          ncovv++; /* Varying variables without age */
                   10915:          TvarV[ncovv]=Tvar[k];
                   10916:          TvarVind[ncovv]=k;
                   10917:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10918:          Fixed[k]= 1;
                   10919:          Dummy[k]= 1;
                   10920:          modell[k].maintype= VTYPE;
                   10921:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10922:          ncovv++; /* Varying variables without age */
                   10923:          TvarV[ncovv]=Tvar[k];
                   10924:          TvarVind[ncovv]=k;
                   10925:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10926:          Fixed[k]= 1;
                   10927:          Dummy[k]= 1;
                   10928:          modell[k].maintype= VTYPE;
                   10929:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10930:          ncovv++; /* Varying variables without age */
                   10931:          TvarV[ncovv]=Tvar[k];
                   10932:          TvarVind[ncovv]=k;
                   10933:        }
1.227     brouard  10934:       }else{
1.240     brouard  10935:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10936:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10937:       } /*end k1*/
1.225     brouard  10938:     }else{
1.226     brouard  10939:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10940:       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  10941:     }
1.227     brouard  10942:     printf("Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
1.231     brouard  10943:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10944:     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]);
                   10945:   }
                   10946:   /* Searching for doublons in the model */
                   10947:   for(k1=1; k1<= cptcovt;k1++){
                   10948:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10949:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10950:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10951:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10952:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10953:            printf("Error duplication in the model=%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]);
                   10954:            fprintf(ficlog,"Error duplication in the model=%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  10955:            return(1);
                   10956:          }
                   10957:        }else if (Typevar[k1] ==2){
                   10958:          k3=Tposprod[k1];
                   10959:          k4=Tposprod[k2];
                   10960:          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])) ){
                   10961:            printf("Error duplication in the model=%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]]);
                   10962:            fprintf(ficlog,"Error duplication in the model=%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);
                   10963:            return(1);
                   10964:          }
                   10965:        }
1.227     brouard  10966:       }
                   10967:     }
1.225     brouard  10968:   }
                   10969:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10970:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10971:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10972:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10973:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10974:   /*endread:*/
1.225     brouard  10975:   printf("Exiting decodemodel: ");
                   10976:   return (1);
1.136     brouard  10977: }
                   10978: 
1.169     brouard  10979: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10980: {/* Check ages at death */
1.136     brouard  10981:   int i, m;
1.218     brouard  10982:   int firstone=0;
                   10983:   
1.136     brouard  10984:   for (i=1; i<=imx; i++) {
                   10985:     for(m=2; (m<= maxwav); m++) {
                   10986:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10987:        anint[m][i]=9999;
1.216     brouard  10988:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10989:          s[m][i]=-1;
1.136     brouard  10990:       }
                   10991:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10992:        *nberr = *nberr + 1;
1.218     brouard  10993:        if(firstone == 0){
                   10994:          firstone=1;
1.260     brouard  10995:        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  10996:        }
1.262     brouard  10997:        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  10998:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10999:       }
                   11000:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11001:        (*nberr)++;
1.259     brouard  11002:        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  11003:        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  11004:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11005:       }
                   11006:     }
                   11007:   }
                   11008: 
                   11009:   for (i=1; i<=imx; i++)  {
                   11010:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11011:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11012:       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  11013:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11014:          if(agedc[i]>0){
                   11015:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11016:              agev[m][i]=agedc[i];
1.214     brouard  11017:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11018:            }else {
1.136     brouard  11019:              if ((int)andc[i]!=9999){
                   11020:                nbwarn++;
                   11021:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11022:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11023:                agev[m][i]=-1;
                   11024:              }
                   11025:            }
1.169     brouard  11026:          } /* agedc > 0 */
1.214     brouard  11027:        } /* end if */
1.136     brouard  11028:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11029:                                 years but with the precision of a month */
                   11030:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11031:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11032:            agev[m][i]=1;
                   11033:          else if(agev[m][i] < *agemin){ 
                   11034:            *agemin=agev[m][i];
                   11035:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11036:          }
                   11037:          else if(agev[m][i] >*agemax){
                   11038:            *agemax=agev[m][i];
1.156     brouard  11039:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11040:          }
                   11041:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11042:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11043:        } /* en if 9*/
1.136     brouard  11044:        else { /* =9 */
1.214     brouard  11045:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11046:          agev[m][i]=1;
                   11047:          s[m][i]=-1;
                   11048:        }
                   11049:       }
1.214     brouard  11050:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11051:        agev[m][i]=1;
1.214     brouard  11052:       else{
                   11053:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11054:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11055:        agev[m][i]=0;
                   11056:       }
                   11057:     } /* End for lastpass */
                   11058:   }
1.136     brouard  11059:     
                   11060:   for (i=1; i<=imx; i++)  {
                   11061:     for(m=firstpass; (m<=lastpass); m++){
                   11062:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11063:        (*nberr)++;
1.136     brouard  11064:        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);     
                   11065:        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);     
                   11066:        return 1;
                   11067:       }
                   11068:     }
                   11069:   }
                   11070: 
                   11071:   /*for (i=1; i<=imx; i++){
                   11072:   for (m=firstpass; (m<lastpass); m++){
                   11073:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11074: }
                   11075: 
                   11076: }*/
                   11077: 
                   11078: 
1.139     brouard  11079:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11080:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11081: 
                   11082:   return (0);
1.164     brouard  11083:  /* endread:*/
1.136     brouard  11084:     printf("Exiting calandcheckages: ");
                   11085:     return (1);
                   11086: }
                   11087: 
1.172     brouard  11088: #if defined(_MSC_VER)
                   11089: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11090: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11091: //#include "stdafx.h"
                   11092: //#include <stdio.h>
                   11093: //#include <tchar.h>
                   11094: //#include <windows.h>
                   11095: //#include <iostream>
                   11096: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11097: 
                   11098: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11099: 
                   11100: BOOL IsWow64()
                   11101: {
                   11102:        BOOL bIsWow64 = FALSE;
                   11103: 
                   11104:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11105:        //  (HANDLE, PBOOL);
                   11106: 
                   11107:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11108: 
                   11109:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11110:        const char funcName[] = "IsWow64Process";
                   11111:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11112:                GetProcAddress(module, funcName);
                   11113: 
                   11114:        if (NULL != fnIsWow64Process)
                   11115:        {
                   11116:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11117:                        &bIsWow64))
                   11118:                        //throw std::exception("Unknown error");
                   11119:                        printf("Unknown error\n");
                   11120:        }
                   11121:        return bIsWow64 != FALSE;
                   11122: }
                   11123: #endif
1.177     brouard  11124: 
1.191     brouard  11125: void syscompilerinfo(int logged)
1.292     brouard  11126: {
                   11127: #include <stdint.h>
                   11128: 
                   11129:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11130:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11131:    /* /GS /W3 /Gy
                   11132:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11133:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11134:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11135:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11136:    */ 
                   11137:    /* 64 bits */
1.185     brouard  11138:    /*
                   11139:      /GS /W3 /Gy
                   11140:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11141:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11142:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11143:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11144:    /* Optimization are useless and O3 is slower than O2 */
                   11145:    /*
                   11146:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11147:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11148:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11149:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11150:    */
1.186     brouard  11151:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11152:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11153:       /PDB:"visual studio
                   11154:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11155:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11156:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11157:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11158:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11159:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11160:       uiAccess='false'"
                   11161:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11162:       /NOLOGO /TLBID:1
                   11163:    */
1.292     brouard  11164: 
                   11165: 
1.177     brouard  11166: #if defined __INTEL_COMPILER
1.178     brouard  11167: #if defined(__GNUC__)
                   11168:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11169: #endif
1.177     brouard  11170: #elif defined(__GNUC__) 
1.179     brouard  11171: #ifndef  __APPLE__
1.174     brouard  11172: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11173: #endif
1.177     brouard  11174:    struct utsname sysInfo;
1.178     brouard  11175:    int cross = CROSS;
                   11176:    if (cross){
                   11177:           printf("Cross-");
1.191     brouard  11178:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11179:    }
1.174     brouard  11180: #endif
                   11181: 
1.191     brouard  11182:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11183: #if defined(__clang__)
1.191     brouard  11184:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11185: #endif
                   11186: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11187:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11188: #endif
                   11189: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11190:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11191: #endif
                   11192: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11193:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11194: #endif
                   11195: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11196:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11197: #endif
                   11198: #if defined(_MSC_VER)
1.191     brouard  11199:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11200: #endif
                   11201: #if defined(__PGI)
1.191     brouard  11202:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11203: #endif
                   11204: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11205:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11206: #endif
1.191     brouard  11207:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11208:    
1.167     brouard  11209: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11210: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11211:     // Windows (x64 and x86)
1.191     brouard  11212:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11213: #elif __unix__ // all unices, not all compilers
                   11214:     // Unix
1.191     brouard  11215:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11216: #elif __linux__
                   11217:     // linux
1.191     brouard  11218:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11219: #elif __APPLE__
1.174     brouard  11220:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11221:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11222: #endif
                   11223: 
                   11224: /*  __MINGW32__          */
                   11225: /*  __CYGWIN__  */
                   11226: /* __MINGW64__  */
                   11227: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11228: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11229: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11230: /* _WIN64  // Defined for applications for Win64. */
                   11231: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11232: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11233: 
1.167     brouard  11234: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11235:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11236: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11237:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11238: #else
1.191     brouard  11239:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11240: #endif
                   11241: 
1.169     brouard  11242: #if defined(__GNUC__)
                   11243: # if defined(__GNUC_PATCHLEVEL__)
                   11244: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11245:                             + __GNUC_MINOR__ * 100 \
                   11246:                             + __GNUC_PATCHLEVEL__)
                   11247: # else
                   11248: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11249:                             + __GNUC_MINOR__ * 100)
                   11250: # endif
1.174     brouard  11251:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11252:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11253: 
                   11254:    if (uname(&sysInfo) != -1) {
                   11255:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11256:         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  11257:    }
                   11258:    else
                   11259:       perror("uname() error");
1.179     brouard  11260:    //#ifndef __INTEL_COMPILER 
                   11261: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11262:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11263:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11264: #endif
1.169     brouard  11265: #endif
1.172     brouard  11266: 
1.286     brouard  11267:    //   void main ()
1.172     brouard  11268:    //   {
1.169     brouard  11269: #if defined(_MSC_VER)
1.174     brouard  11270:    if (IsWow64()){
1.191     brouard  11271:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11272:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11273:    }
                   11274:    else{
1.191     brouard  11275:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11276:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11277:    }
1.172     brouard  11278:    //     printf("\nPress Enter to continue...");
                   11279:    //     getchar();
                   11280:    //   }
                   11281: 
1.169     brouard  11282: #endif
                   11283:    
1.167     brouard  11284: 
1.219     brouard  11285: }
1.136     brouard  11286: 
1.219     brouard  11287: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11288:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11289:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11290:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11291:   /* double ftolpl = 1.e-10; */
1.180     brouard  11292:   double age, agebase, agelim;
1.203     brouard  11293:   double tot;
1.180     brouard  11294: 
1.202     brouard  11295:   strcpy(filerespl,"PL_");
                   11296:   strcat(filerespl,fileresu);
                   11297:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11298:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11299:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11300:   }
1.288     brouard  11301:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11302:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11303:   pstamp(ficrespl);
1.288     brouard  11304:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11305:   fprintf(ficrespl,"#Age ");
                   11306:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11307:   fprintf(ficrespl,"\n");
1.180     brouard  11308:   
1.219     brouard  11309:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11310: 
1.219     brouard  11311:   agebase=ageminpar;
                   11312:   agelim=agemaxpar;
1.180     brouard  11313: 
1.227     brouard  11314:   /* i1=pow(2,ncoveff); */
1.234     brouard  11315:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11316:   if (cptcovn < 1){i1=1;}
1.180     brouard  11317: 
1.238     brouard  11318:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   11319:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  11320:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11321:        continue;
1.235     brouard  11322: 
1.238     brouard  11323:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11324:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11325:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11326:       /* k=k+1; */
                   11327:       /* to clean */
1.332     brouard  11328:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11329:       fprintf(ficrespl,"#******");
                   11330:       printf("#******");
                   11331:       fprintf(ficlog,"#******");
                   11332:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11333:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
                   11334:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* Here problem for varying dummy*/
                   11335:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11336:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11337:       }
                   11338:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11339:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11340:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11341:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11342:       }
                   11343:       fprintf(ficrespl,"******\n");
                   11344:       printf("******\n");
                   11345:       fprintf(ficlog,"******\n");
                   11346:       if(invalidvarcomb[k]){
                   11347:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11348:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11349:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11350:        continue;
                   11351:       }
1.219     brouard  11352: 
1.238     brouard  11353:       fprintf(ficrespl,"#Age ");
                   11354:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11355:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11356:       }
                   11357:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11358:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11359:     
1.238     brouard  11360:       for (age=agebase; age<=agelim; age++){
                   11361:        /* for (age=agebase; age<=agebase; age++){ */
                   11362:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   11363:        fprintf(ficrespl,"%.0f ",age );
                   11364:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11365:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11366:        tot=0.;
                   11367:        for(i=1; i<=nlstate;i++){
                   11368:          tot +=  prlim[i][i];
                   11369:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11370:        }
                   11371:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11372:       } /* Age */
                   11373:       /* was end of cptcod */
                   11374:     } /* cptcov */
                   11375:   } /* nres */
1.219     brouard  11376:   return 0;
1.180     brouard  11377: }
                   11378: 
1.218     brouard  11379: 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  11380:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11381:        
                   11382:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11383:    * at any age between ageminpar and agemaxpar
                   11384:         */
1.235     brouard  11385:   int i, j, k, i1, nres=0 ;
1.217     brouard  11386:   /* double ftolpl = 1.e-10; */
                   11387:   double age, agebase, agelim;
                   11388:   double tot;
1.218     brouard  11389:   /* double ***mobaverage; */
                   11390:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11391: 
                   11392:   strcpy(fileresplb,"PLB_");
                   11393:   strcat(fileresplb,fileresu);
                   11394:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11395:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11396:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11397:   }
1.288     brouard  11398:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11399:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11400:   pstamp(ficresplb);
1.288     brouard  11401:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11402:   fprintf(ficresplb,"#Age ");
                   11403:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11404:   fprintf(ficresplb,"\n");
                   11405:   
1.218     brouard  11406:   
                   11407:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11408:   
                   11409:   agebase=ageminpar;
                   11410:   agelim=agemaxpar;
                   11411:   
                   11412:   
1.227     brouard  11413:   i1=pow(2,cptcoveff);
1.218     brouard  11414:   if (cptcovn < 1){i1=1;}
1.227     brouard  11415:   
1.238     brouard  11416:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11417:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11418:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11419:        continue;
1.332     brouard  11420:      /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11421:       fprintf(ficresplb,"#******");
                   11422:       printf("#******");
                   11423:       fprintf(ficlog,"#******");
                   11424:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11425:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11426:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11427:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11428:       }
                   11429:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11430:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11431:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11432:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11433:       }
                   11434:       fprintf(ficresplb,"******\n");
                   11435:       printf("******\n");
                   11436:       fprintf(ficlog,"******\n");
                   11437:       if(invalidvarcomb[k]){
                   11438:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11439:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11440:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11441:        continue;
                   11442:       }
1.218     brouard  11443:     
1.238     brouard  11444:       fprintf(ficresplb,"#Age ");
                   11445:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11446:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11447:       }
                   11448:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11449:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11450:     
                   11451:     
1.238     brouard  11452:       for (age=agebase; age<=agelim; age++){
                   11453:        /* for (age=agebase; age<=agebase; age++){ */
                   11454:        if(mobilavproj > 0){
                   11455:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11456:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11457:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11458:        }else if (mobilavproj == 0){
                   11459:          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);
                   11460:          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);
                   11461:          exit(1);
                   11462:        }else{
                   11463:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11464:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11465:          /* printf("TOTOT\n"); */
                   11466:           /* exit(1); */
1.238     brouard  11467:        }
                   11468:        fprintf(ficresplb,"%.0f ",age );
                   11469:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11470:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11471:        tot=0.;
                   11472:        for(i=1; i<=nlstate;i++){
                   11473:          tot +=  bprlim[i][i];
                   11474:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11475:        }
                   11476:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11477:       } /* Age */
                   11478:       /* was end of cptcod */
1.255     brouard  11479:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11480:     } /* end of any combination */
                   11481:   } /* end of nres */  
1.218     brouard  11482:   /* hBijx(p, bage, fage); */
                   11483:   /* fclose(ficrespijb); */
                   11484:   
                   11485:   return 0;
1.217     brouard  11486: }
1.218     brouard  11487:  
1.180     brouard  11488: int hPijx(double *p, int bage, int fage){
                   11489:     /*------------- h Pij x at various ages ------------*/
                   11490: 
                   11491:   int stepsize;
                   11492:   int agelim;
                   11493:   int hstepm;
                   11494:   int nhstepm;
1.235     brouard  11495:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11496: 
                   11497:   double agedeb;
                   11498:   double ***p3mat;
                   11499: 
1.201     brouard  11500:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11501:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11502:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11503:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11504:     }
                   11505:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11506:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11507:   
                   11508:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11509:     /*if (stepm<=24) stepsize=2;*/
                   11510: 
                   11511:     agelim=AGESUP;
                   11512:     hstepm=stepsize*YEARM; /* Every year of age */
                   11513:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11514:                
1.180     brouard  11515:     /* hstepm=1;   aff par mois*/
                   11516:     pstamp(ficrespij);
                   11517:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11518:     i1= pow(2,cptcoveff);
1.218     brouard  11519:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11520:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11521:                /*      k=k+1;  */
1.235     brouard  11522:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11523:     for(k=1; k<=i1;k++){
1.253     brouard  11524:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11525:        continue;
1.183     brouard  11526:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11527:       for(j=1;j<=cptcoveff;j++) 
1.332     brouard  11528:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  11529:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11530:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11531:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11532:       }
1.183     brouard  11533:       fprintf(ficrespij,"******\n");
                   11534:       
                   11535:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11536:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11537:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11538:        
                   11539:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11540:        
1.183     brouard  11541:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11542:        oldm=oldms;savm=savms;
1.235     brouard  11543:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11544:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11545:        for(i=1; i<=nlstate;i++)
                   11546:          for(j=1; j<=nlstate+ndeath;j++)
                   11547:            fprintf(ficrespij," %1d-%1d",i,j);
                   11548:        fprintf(ficrespij,"\n");
                   11549:        for (h=0; h<=nhstepm; h++){
                   11550:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11551:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11552:          for(i=1; i<=nlstate;i++)
                   11553:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11554:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11555:          fprintf(ficrespij,"\n");
                   11556:        }
1.183     brouard  11557:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11558:        fprintf(ficrespij,"\n");
                   11559:       }
1.180     brouard  11560:       /*}*/
                   11561:     }
1.218     brouard  11562:     return 0;
1.180     brouard  11563: }
1.218     brouard  11564:  
                   11565:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11566:     /*------------- h Bij x at various ages ------------*/
                   11567: 
                   11568:   int stepsize;
1.218     brouard  11569:   /* int agelim; */
                   11570:        int ageminl;
1.217     brouard  11571:   int hstepm;
                   11572:   int nhstepm;
1.238     brouard  11573:   int h, i, i1, j, k, nres;
1.218     brouard  11574:        
1.217     brouard  11575:   double agedeb;
                   11576:   double ***p3mat;
1.218     brouard  11577:        
                   11578:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11579:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11580:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11581:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11582:   }
                   11583:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11584:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11585:   
                   11586:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11587:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11588:   
1.218     brouard  11589:   /* agelim=AGESUP; */
1.289     brouard  11590:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11591:   hstepm=stepsize*YEARM; /* Every year of age */
                   11592:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11593:   
                   11594:   /* hstepm=1;   aff par mois*/
                   11595:   pstamp(ficrespijb);
1.255     brouard  11596:   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  11597:   i1= pow(2,cptcoveff);
1.218     brouard  11598:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11599:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11600:   /*   k=k+1;  */
1.238     brouard  11601:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11602:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11603:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11604:        continue;
                   11605:       fprintf(ficrespijb,"\n#****** ");
                   11606:       for(j=1;j<=cptcoveff;j++)
1.332     brouard  11607:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11608:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11609:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11610:       }
                   11611:       fprintf(ficrespijb,"******\n");
1.264     brouard  11612:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11613:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11614:        continue;
                   11615:       }
                   11616:       
                   11617:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11618:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11619:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11620:        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 */
                   11621:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11622:        
                   11623:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11624:        
1.266     brouard  11625:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11626:        /* and memory limitations if stepm is small */
                   11627: 
1.238     brouard  11628:        /* oldm=oldms;savm=savms; */
                   11629:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11630:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11631:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11632:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11633:        for(i=1; i<=nlstate;i++)
                   11634:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11635:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11636:        fprintf(ficrespijb,"\n");
1.238     brouard  11637:        for (h=0; h<=nhstepm; h++){
                   11638:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11639:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11640:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11641:          for(i=1; i<=nlstate;i++)
                   11642:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11643:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11644:          fprintf(ficrespijb,"\n");
                   11645:        }
                   11646:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11647:        fprintf(ficrespijb,"\n");
                   11648:       } /* end age deb */
                   11649:     } /* end combination */
                   11650:   } /* end nres */
1.218     brouard  11651:   return 0;
                   11652:  } /*  hBijx */
1.217     brouard  11653: 
1.180     brouard  11654: 
1.136     brouard  11655: /***********************************************/
                   11656: /**************** Main Program *****************/
                   11657: /***********************************************/
                   11658: 
                   11659: int main(int argc, char *argv[])
                   11660: {
                   11661: #ifdef GSL
                   11662:   const gsl_multimin_fminimizer_type *T;
                   11663:   size_t iteri = 0, it;
                   11664:   int rval = GSL_CONTINUE;
                   11665:   int status = GSL_SUCCESS;
                   11666:   double ssval;
                   11667: #endif
                   11668:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11669:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11670:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11671:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11672:   int jj, ll, li, lj, lk;
1.136     brouard  11673:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11674:   int num_filled;
1.136     brouard  11675:   int itimes;
                   11676:   int NDIM=2;
                   11677:   int vpopbased=0;
1.235     brouard  11678:   int nres=0;
1.258     brouard  11679:   int endishere=0;
1.277     brouard  11680:   int noffset=0;
1.274     brouard  11681:   int ncurrv=0; /* Temporary variable */
                   11682:   
1.164     brouard  11683:   char ca[32], cb[32];
1.136     brouard  11684:   /*  FILE *fichtm; *//* Html File */
                   11685:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11686:   struct stat info;
1.191     brouard  11687:   double agedeb=0.;
1.194     brouard  11688: 
                   11689:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11690:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11691: 
1.165     brouard  11692:   double fret;
1.191     brouard  11693:   double dum=0.; /* Dummy variable */
1.136     brouard  11694:   double ***p3mat;
1.218     brouard  11695:   /* double ***mobaverage; */
1.319     brouard  11696:   double wald;
1.164     brouard  11697: 
                   11698:   char line[MAXLINE];
1.197     brouard  11699:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11700: 
1.234     brouard  11701:   char  modeltemp[MAXLINE];
1.332     brouard  11702:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  11703:   
1.136     brouard  11704:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11705:   char *tok, *val; /* pathtot */
1.290     brouard  11706:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11707:   int c,  h , cpt, c2;
1.191     brouard  11708:   int jl=0;
                   11709:   int i1, j1, jk, stepsize=0;
1.194     brouard  11710:   int count=0;
                   11711: 
1.164     brouard  11712:   int *tab; 
1.136     brouard  11713:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11714:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11715:   /* double anprojf, mprojf, jprojf; */
                   11716:   /* double jintmean,mintmean,aintmean;   */
                   11717:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11718:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11719:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11720:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11721:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11722:   int mobilav=0,popforecast=0;
1.191     brouard  11723:   int hstepm=0, nhstepm=0;
1.136     brouard  11724:   int agemortsup;
                   11725:   float  sumlpop=0.;
                   11726:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11727:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11728: 
1.191     brouard  11729:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11730:   double ftolpl=FTOL;
                   11731:   double **prlim;
1.217     brouard  11732:   double **bprlim;
1.317     brouard  11733:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11734:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11735:   double ***paramstart; /* Matrix of starting parameter values */
                   11736:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11737:   double **matcov; /* Matrix of covariance */
1.203     brouard  11738:   double **hess; /* Hessian matrix */
1.136     brouard  11739:   double ***delti3; /* Scale */
                   11740:   double *delti; /* Scale */
                   11741:   double ***eij, ***vareij;
                   11742:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11743: 
1.136     brouard  11744:   double *epj, vepp;
1.164     brouard  11745: 
1.273     brouard  11746:   double dateprev1, dateprev2;
1.296     brouard  11747:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11748:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11749: 
1.217     brouard  11750: 
1.136     brouard  11751:   double **ximort;
1.145     brouard  11752:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11753:   int *dcwave;
                   11754: 
1.164     brouard  11755:   char z[1]="c";
1.136     brouard  11756: 
                   11757:   /*char  *strt;*/
                   11758:   char strtend[80];
1.126     brouard  11759: 
1.164     brouard  11760: 
1.126     brouard  11761: /*   setlocale (LC_ALL, ""); */
                   11762: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11763: /*   textdomain (PACKAGE); */
                   11764: /*   setlocale (LC_CTYPE, ""); */
                   11765: /*   setlocale (LC_MESSAGES, ""); */
                   11766: 
                   11767:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11768:   rstart_time = time(NULL);  
                   11769:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11770:   start_time = *localtime(&rstart_time);
1.126     brouard  11771:   curr_time=start_time;
1.157     brouard  11772:   /*tml = *localtime(&start_time.tm_sec);*/
                   11773:   /* strcpy(strstart,asctime(&tml)); */
                   11774:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11775: 
                   11776: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11777: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11778: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11779: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11780: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11781: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11782: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11783: /*   strt=asctime(&tmg); */
                   11784: /*   printf("Time(after) =%s",strstart);  */
                   11785: /*  (void) time (&time_value);
                   11786: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11787: *  tm = *localtime(&time_value);
                   11788: *  strstart=asctime(&tm);
                   11789: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11790: */
                   11791: 
                   11792:   nberr=0; /* Number of errors and warnings */
                   11793:   nbwarn=0;
1.184     brouard  11794: #ifdef WIN32
                   11795:   _getcwd(pathcd, size);
                   11796: #else
1.126     brouard  11797:   getcwd(pathcd, size);
1.184     brouard  11798: #endif
1.191     brouard  11799:   syscompilerinfo(0);
1.196     brouard  11800:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11801:   if(argc <=1){
                   11802:     printf("\nEnter the parameter file name: ");
1.205     brouard  11803:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11804:       printf("ERROR Empty parameter file name\n");
                   11805:       goto end;
                   11806:     }
1.126     brouard  11807:     i=strlen(pathr);
                   11808:     if(pathr[i-1]=='\n')
                   11809:       pathr[i-1]='\0';
1.156     brouard  11810:     i=strlen(pathr);
1.205     brouard  11811:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11812:       pathr[i-1]='\0';
1.205     brouard  11813:     }
                   11814:     i=strlen(pathr);
                   11815:     if( i==0 ){
                   11816:       printf("ERROR Empty parameter file name\n");
                   11817:       goto end;
                   11818:     }
                   11819:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11820:       printf("Pathr |%s|\n",pathr);
                   11821:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11822:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11823:       strcpy (pathtot, val);
                   11824:       if(pathr[0] == '\0') break; /* Dirty */
                   11825:     }
                   11826:   }
1.281     brouard  11827:   else if (argc<=2){
                   11828:     strcpy(pathtot,argv[1]);
                   11829:   }
1.126     brouard  11830:   else{
                   11831:     strcpy(pathtot,argv[1]);
1.281     brouard  11832:     strcpy(z,argv[2]);
                   11833:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11834:   }
                   11835:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11836:   /*cygwin_split_path(pathtot,path,optionfile);
                   11837:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11838:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11839: 
                   11840:   /* Split argv[0], imach program to get pathimach */
                   11841:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11842:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11843:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11844:  /*   strcpy(pathimach,argv[0]); */
                   11845:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11846:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11847:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11848: #ifdef WIN32
                   11849:   _chdir(path); /* Can be a relative path */
                   11850:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11851: #else
1.126     brouard  11852:   chdir(path); /* Can be a relative path */
1.184     brouard  11853:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11854: #endif
                   11855:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11856:   strcpy(command,"mkdir ");
                   11857:   strcat(command,optionfilefiname);
                   11858:   if((outcmd=system(command)) != 0){
1.169     brouard  11859:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11860:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11861:     /* fclose(ficlog); */
                   11862: /*     exit(1); */
                   11863:   }
                   11864: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11865: /*     perror("mkdir"); */
                   11866: /*   } */
                   11867: 
                   11868:   /*-------- arguments in the command line --------*/
                   11869: 
1.186     brouard  11870:   /* Main Log file */
1.126     brouard  11871:   strcat(filelog, optionfilefiname);
                   11872:   strcat(filelog,".log");    /* */
                   11873:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11874:     printf("Problem with logfile %s\n",filelog);
                   11875:     goto end;
                   11876:   }
                   11877:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11878:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11879:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11880:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11881:  path=%s \n\
                   11882:  optionfile=%s\n\
                   11883:  optionfilext=%s\n\
1.156     brouard  11884:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11885: 
1.197     brouard  11886:   syscompilerinfo(1);
1.167     brouard  11887: 
1.126     brouard  11888:   printf("Local time (at start):%s",strstart);
                   11889:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11890:   fflush(ficlog);
                   11891: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11892: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11893: 
                   11894:   /* */
                   11895:   strcpy(fileres,"r");
                   11896:   strcat(fileres, optionfilefiname);
1.201     brouard  11897:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11898:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11899:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11900: 
1.186     brouard  11901:   /* Main ---------arguments file --------*/
1.126     brouard  11902: 
                   11903:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11904:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11905:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11906:     fflush(ficlog);
1.149     brouard  11907:     /* goto end; */
                   11908:     exit(70); 
1.126     brouard  11909:   }
                   11910: 
                   11911:   strcpy(filereso,"o");
1.201     brouard  11912:   strcat(filereso,fileresu);
1.126     brouard  11913:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11914:     printf("Problem with Output resultfile: %s\n", filereso);
                   11915:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11916:     fflush(ficlog);
                   11917:     goto end;
                   11918:   }
1.278     brouard  11919:       /*-------- Rewriting parameter file ----------*/
                   11920:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11921:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11922:   strcat(rfileres,".");    /* */
                   11923:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11924:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11925:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11926:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11927:     fflush(ficlog);
                   11928:     goto end;
                   11929:   }
                   11930:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11931: 
1.278     brouard  11932:                                      
1.126     brouard  11933:   /* Reads comments: lines beginning with '#' */
                   11934:   numlinepar=0;
1.277     brouard  11935:   /* Is it a BOM UTF-8 Windows file? */
                   11936:   /* First parameter line */
1.197     brouard  11937:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11938:     noffset=0;
                   11939:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11940:     {
                   11941:       noffset=noffset+3;
                   11942:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11943:     }
1.302     brouard  11944: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11945:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11946:     {
                   11947:       noffset=noffset+2;
                   11948:       printf("# File is an UTF16BE BOM file\n");
                   11949:     }
                   11950:     else if( line[0] == 0 && line[1] == 0)
                   11951:     {
                   11952:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11953:        noffset=noffset+4;
                   11954:        printf("# File is an UTF16BE BOM file\n");
                   11955:       }
                   11956:     } else{
                   11957:       ;/*printf(" Not a BOM file\n");*/
                   11958:     }
                   11959:   
1.197     brouard  11960:     /* If line starts with a # it is a comment */
1.277     brouard  11961:     if (line[noffset] == '#') {
1.197     brouard  11962:       numlinepar++;
                   11963:       fputs(line,stdout);
                   11964:       fputs(line,ficparo);
1.278     brouard  11965:       fputs(line,ficres);
1.197     brouard  11966:       fputs(line,ficlog);
                   11967:       continue;
                   11968:     }else
                   11969:       break;
                   11970:   }
                   11971:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11972:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11973:     if (num_filled != 5) {
                   11974:       printf("Should be 5 parameters\n");
1.283     brouard  11975:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11976:     }
1.126     brouard  11977:     numlinepar++;
1.197     brouard  11978:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11979:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11980:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11981:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11982:   }
                   11983:   /* Second parameter line */
                   11984:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11985:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11986:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11987:     if (line[0] == '#') {
                   11988:       numlinepar++;
1.283     brouard  11989:       printf("%s",line);
                   11990:       fprintf(ficres,"%s",line);
                   11991:       fprintf(ficparo,"%s",line);
                   11992:       fprintf(ficlog,"%s",line);
1.197     brouard  11993:       continue;
                   11994:     }else
                   11995:       break;
                   11996:   }
1.223     brouard  11997:   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", \
                   11998:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11999:     if (num_filled != 11) {
                   12000:       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  12001:       printf("but line=%s\n",line);
1.283     brouard  12002:       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");
                   12003:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12004:     }
1.286     brouard  12005:     if( lastpass > maxwav){
                   12006:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12007:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12008:       fflush(ficlog);
                   12009:       goto end;
                   12010:     }
                   12011:       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  12012:     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  12013:     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  12014:     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  12015:   }
1.203     brouard  12016:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12017:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12018:   /* Third parameter line */
                   12019:   while(fgets(line, MAXLINE, ficpar)) {
                   12020:     /* If line starts with a # it is a comment */
                   12021:     if (line[0] == '#') {
                   12022:       numlinepar++;
1.283     brouard  12023:       printf("%s",line);
                   12024:       fprintf(ficres,"%s",line);
                   12025:       fprintf(ficparo,"%s",line);
                   12026:       fprintf(ficlog,"%s",line);
1.197     brouard  12027:       continue;
                   12028:     }else
                   12029:       break;
                   12030:   }
1.201     brouard  12031:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12032:     if (num_filled != 1){
1.302     brouard  12033:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12034:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12035:       model[0]='\0';
                   12036:       goto end;
                   12037:     }
                   12038:     else{
                   12039:       if (model[0]=='+'){
                   12040:        for(i=1; i<=strlen(model);i++)
                   12041:          modeltemp[i-1]=model[i];
1.201     brouard  12042:        strcpy(model,modeltemp); 
1.197     brouard  12043:       }
                   12044:     }
1.199     brouard  12045:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12046:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12047:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12048:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12049:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12050:   }
                   12051:   /* 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); */
                   12052:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12053:   /* 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  12054:   /* 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); */
                   12055:   /* 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  12056:   fflush(ficlog);
1.190     brouard  12057:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12058:   if(model[0]=='#'){
1.279     brouard  12059:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12060:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12061:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12062:     if(mle != -1){
1.279     brouard  12063:       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  12064:       exit(1);
                   12065:     }
                   12066:   }
1.126     brouard  12067:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12068:     ungetc(c,ficpar);
                   12069:     fgets(line, MAXLINE, ficpar);
                   12070:     numlinepar++;
1.195     brouard  12071:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12072:       z[0]=line[1];
                   12073:     }
                   12074:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12075:     fputs(line, stdout);
                   12076:     //puts(line);
1.126     brouard  12077:     fputs(line,ficparo);
                   12078:     fputs(line,ficlog);
                   12079:   }
                   12080:   ungetc(c,ficpar);
                   12081: 
                   12082:    
1.290     brouard  12083:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12084:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12085:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12086:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  12087:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12088:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12089:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12090:   */
                   12091:   if (strlen(model)>1) 
1.187     brouard  12092:     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  12093:   else
1.187     brouard  12094:     ncovmodel=2; /* Constant and age */
1.133     brouard  12095:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12096:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12097:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12098:     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);
                   12099:     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);
                   12100:     fflush(stdout);
                   12101:     fclose (ficlog);
                   12102:     goto end;
                   12103:   }
1.126     brouard  12104:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12105:   delti=delti3[1][1];
                   12106:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12107:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12108: /* We could also provide initial parameters values giving by simple logistic regression 
                   12109:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12110:       /* for(i=1;i<nlstate;i++){ */
                   12111:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12112:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12113:       /* } */
1.126     brouard  12114:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12115:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12116:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12117:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12118:     fclose (ficparo);
                   12119:     fclose (ficlog);
                   12120:     goto end;
                   12121:     exit(0);
1.220     brouard  12122:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12123:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12124:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12125:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12126:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12127:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12128:     hess=matrix(1,npar,1,npar);
1.220     brouard  12129:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12130:     /* Read guessed parameters */
1.126     brouard  12131:     /* Reads comments: lines beginning with '#' */
                   12132:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12133:       ungetc(c,ficpar);
                   12134:       fgets(line, MAXLINE, ficpar);
                   12135:       numlinepar++;
1.141     brouard  12136:       fputs(line,stdout);
1.126     brouard  12137:       fputs(line,ficparo);
                   12138:       fputs(line,ficlog);
                   12139:     }
                   12140:     ungetc(c,ficpar);
                   12141:     
                   12142:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12143:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12144:     for(i=1; i <=nlstate; i++){
1.234     brouard  12145:       j=0;
1.126     brouard  12146:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12147:        if(jj==i) continue;
                   12148:        j++;
1.292     brouard  12149:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12150:          ungetc(c,ficpar);
                   12151:          fgets(line, MAXLINE, ficpar);
                   12152:          numlinepar++;
                   12153:          fputs(line,stdout);
                   12154:          fputs(line,ficparo);
                   12155:          fputs(line,ficlog);
                   12156:        }
                   12157:        ungetc(c,ficpar);
1.234     brouard  12158:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12159:        if ((i1 != i) || (j1 != jj)){
                   12160:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12161: It might be a problem of design; if ncovcol and the model are correct\n \
                   12162: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12163:          exit(1);
                   12164:        }
                   12165:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12166:        if(mle==1)
                   12167:          printf("%1d%1d",i,jj);
                   12168:        fprintf(ficlog,"%1d%1d",i,jj);
                   12169:        for(k=1; k<=ncovmodel;k++){
                   12170:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12171:          if(mle==1){
                   12172:            printf(" %lf",param[i][j][k]);
                   12173:            fprintf(ficlog," %lf",param[i][j][k]);
                   12174:          }
                   12175:          else
                   12176:            fprintf(ficlog," %lf",param[i][j][k]);
                   12177:          fprintf(ficparo," %lf",param[i][j][k]);
                   12178:        }
                   12179:        fscanf(ficpar,"\n");
                   12180:        numlinepar++;
                   12181:        if(mle==1)
                   12182:          printf("\n");
                   12183:        fprintf(ficlog,"\n");
                   12184:        fprintf(ficparo,"\n");
1.126     brouard  12185:       }
                   12186:     }  
                   12187:     fflush(ficlog);
1.234     brouard  12188:     
1.251     brouard  12189:     /* Reads parameters values */
1.126     brouard  12190:     p=param[1][1];
1.251     brouard  12191:     pstart=paramstart[1][1];
1.126     brouard  12192:     
                   12193:     /* Reads comments: lines beginning with '#' */
                   12194:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12195:       ungetc(c,ficpar);
                   12196:       fgets(line, MAXLINE, ficpar);
                   12197:       numlinepar++;
1.141     brouard  12198:       fputs(line,stdout);
1.126     brouard  12199:       fputs(line,ficparo);
                   12200:       fputs(line,ficlog);
                   12201:     }
                   12202:     ungetc(c,ficpar);
                   12203: 
                   12204:     for(i=1; i <=nlstate; i++){
                   12205:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12206:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12207:        if ( (i1-i) * (j1-j) != 0){
                   12208:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12209:          exit(1);
                   12210:        }
                   12211:        printf("%1d%1d",i,j);
                   12212:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12213:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12214:        for(k=1; k<=ncovmodel;k++){
                   12215:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12216:          printf(" %le",delti3[i][j][k]);
                   12217:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12218:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12219:        }
                   12220:        fscanf(ficpar,"\n");
                   12221:        numlinepar++;
                   12222:        printf("\n");
                   12223:        fprintf(ficparo,"\n");
                   12224:        fprintf(ficlog,"\n");
1.126     brouard  12225:       }
                   12226:     }
                   12227:     fflush(ficlog);
1.234     brouard  12228:     
1.145     brouard  12229:     /* Reads covariance matrix */
1.126     brouard  12230:     delti=delti3[1][1];
1.220     brouard  12231:                
                   12232:                
1.126     brouard  12233:     /* 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  12234:                
1.126     brouard  12235:     /* Reads comments: lines beginning with '#' */
                   12236:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12237:       ungetc(c,ficpar);
                   12238:       fgets(line, MAXLINE, ficpar);
                   12239:       numlinepar++;
1.141     brouard  12240:       fputs(line,stdout);
1.126     brouard  12241:       fputs(line,ficparo);
                   12242:       fputs(line,ficlog);
                   12243:     }
                   12244:     ungetc(c,ficpar);
1.220     brouard  12245:                
1.126     brouard  12246:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12247:     hess=matrix(1,npar,1,npar);
1.131     brouard  12248:     for(i=1; i <=npar; i++)
                   12249:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12250:                
1.194     brouard  12251:     /* Scans npar lines */
1.126     brouard  12252:     for(i=1; i <=npar; i++){
1.226     brouard  12253:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12254:       if(count != 3){
1.226     brouard  12255:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12256: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12257: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12258:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12259: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12260: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12261:        exit(1);
1.220     brouard  12262:       }else{
1.226     brouard  12263:        if(mle==1)
                   12264:          printf("%1d%1d%d",i1,j1,jk);
                   12265:       }
                   12266:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12267:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12268:       for(j=1; j <=i; j++){
1.226     brouard  12269:        fscanf(ficpar," %le",&matcov[i][j]);
                   12270:        if(mle==1){
                   12271:          printf(" %.5le",matcov[i][j]);
                   12272:        }
                   12273:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12274:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12275:       }
                   12276:       fscanf(ficpar,"\n");
                   12277:       numlinepar++;
                   12278:       if(mle==1)
1.220     brouard  12279:                                printf("\n");
1.126     brouard  12280:       fprintf(ficlog,"\n");
                   12281:       fprintf(ficparo,"\n");
                   12282:     }
1.194     brouard  12283:     /* End of read covariance matrix npar lines */
1.126     brouard  12284:     for(i=1; i <=npar; i++)
                   12285:       for(j=i+1;j<=npar;j++)
1.226     brouard  12286:        matcov[i][j]=matcov[j][i];
1.126     brouard  12287:     
                   12288:     if(mle==1)
                   12289:       printf("\n");
                   12290:     fprintf(ficlog,"\n");
                   12291:     
                   12292:     fflush(ficlog);
                   12293:     
                   12294:   }    /* End of mle != -3 */
1.218     brouard  12295:   
1.186     brouard  12296:   /*  Main data
                   12297:    */
1.290     brouard  12298:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12299:   /* num=lvector(1,n); */
                   12300:   /* moisnais=vector(1,n); */
                   12301:   /* annais=vector(1,n); */
                   12302:   /* moisdc=vector(1,n); */
                   12303:   /* andc=vector(1,n); */
                   12304:   /* weight=vector(1,n); */
                   12305:   /* agedc=vector(1,n); */
                   12306:   /* cod=ivector(1,n); */
                   12307:   /* for(i=1;i<=n;i++){ */
                   12308:   num=lvector(firstobs,lastobs);
                   12309:   moisnais=vector(firstobs,lastobs);
                   12310:   annais=vector(firstobs,lastobs);
                   12311:   moisdc=vector(firstobs,lastobs);
                   12312:   andc=vector(firstobs,lastobs);
                   12313:   weight=vector(firstobs,lastobs);
                   12314:   agedc=vector(firstobs,lastobs);
                   12315:   cod=ivector(firstobs,lastobs);
                   12316:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12317:     num[i]=0;
                   12318:     moisnais[i]=0;
                   12319:     annais[i]=0;
                   12320:     moisdc[i]=0;
                   12321:     andc[i]=0;
                   12322:     agedc[i]=0;
                   12323:     cod[i]=0;
                   12324:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12325:   }
1.290     brouard  12326:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12327:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12328:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   12329:   printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel));
1.126     brouard  12330:   tab=ivector(1,NCOVMAX);
1.144     brouard  12331:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12332:   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  12333: 
1.136     brouard  12334:   /* Reads data from file datafile */
                   12335:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12336:     goto end;
                   12337: 
                   12338:   /* Calculation of the number of parameters from char model */
1.234     brouard  12339:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12340:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12341:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12342:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12343:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12344:   */
                   12345:   
                   12346:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12347:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12348:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.234     brouard  12349:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12350:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12351:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12352:   TvarF=ivector(1,NCOVMAX); /*  */
                   12353:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12354:   TvarV=ivector(1,NCOVMAX); /*  */
                   12355:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12356:   TvarA=ivector(1,NCOVMAX); /*  */
                   12357:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12358:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12359:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12360:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12361:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12362:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12363:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12364:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12365:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12366: 
1.230     brouard  12367:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12368:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12369:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12370:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12371:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12372:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12373:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12374:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12375:   */
                   12376:   /* For model-covariate k tells which data-covariate to use but
                   12377:     because this model-covariate is a construction we invent a new column
                   12378:     ncovcol + k1
                   12379:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12380:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12381:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12382:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12383:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12384:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12385:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12386:   */
1.145     brouard  12387:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12388:   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  12389:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12390:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12391:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12392:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12393:                         4 covariates (3 plus signs)
                   12394:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12395:                           */  
                   12396:   for(i=1;i<NCOVMAX;i++)
                   12397:     Tage[i]=0;
1.230     brouard  12398:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12399:                                * individual dummy, fixed or varying:
                   12400:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12401:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12402:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12403:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12404:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12405:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12406:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12407:                                * individual quantitative, fixed or varying:
                   12408:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12409:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12410:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12411: /* Main decodemodel */
                   12412: 
1.187     brouard  12413: 
1.223     brouard  12414:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12415:     goto end;
                   12416: 
1.137     brouard  12417:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12418:     nbwarn++;
                   12419:     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); 
                   12420:     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); 
                   12421:   }
1.136     brouard  12422:     /*  if(mle==1){*/
1.137     brouard  12423:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12424:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12425:   }
                   12426: 
                   12427:     /*-calculation of age at interview from date of interview and age at death -*/
                   12428:   agev=matrix(1,maxwav,1,imx);
                   12429: 
                   12430:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12431:     goto end;
                   12432: 
1.126     brouard  12433: 
1.136     brouard  12434:   agegomp=(int)agemin;
1.290     brouard  12435:   free_vector(moisnais,firstobs,lastobs);
                   12436:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12437:   /* free_matrix(mint,1,maxwav,1,n);
                   12438:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12439:   /* free_vector(moisdc,1,n); */
                   12440:   /* free_vector(andc,1,n); */
1.145     brouard  12441:   /* */
                   12442:   
1.126     brouard  12443:   wav=ivector(1,imx);
1.214     brouard  12444:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12445:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12446:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12447:   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.*/
                   12448:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12449:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12450:    
                   12451:   /* Concatenates waves */
1.214     brouard  12452:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12453:      Death is a valid wave (if date is known).
                   12454:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12455:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12456:      and mw[mi+1][i]. dh depends on stepm.
                   12457:   */
                   12458: 
1.126     brouard  12459:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12460:   /* Concatenates waves */
1.145     brouard  12461:  
1.290     brouard  12462:   free_vector(moisdc,firstobs,lastobs);
                   12463:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12464: 
1.126     brouard  12465:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12466:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12467:   ncodemax[1]=1;
1.145     brouard  12468:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12469:   cptcoveff=0;
1.220     brouard  12470:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12471:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12472:   }
                   12473:   
                   12474:   ncovcombmax=pow(2,cptcoveff);
                   12475:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12476:   for(i=1;i<ncovcombmax;i++)
                   12477:     invalidvarcomb[i]=0;
                   12478:   
1.211     brouard  12479:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12480:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12481:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12482:   
1.200     brouard  12483:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12484:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12485:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12486:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12487:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12488:    * (currently 0 or 1) in the data.
                   12489:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12490:    * corresponding modality (h,j).
                   12491:    */
                   12492: 
1.145     brouard  12493:   h=0;
                   12494:   /*if (cptcovn > 0) */
1.126     brouard  12495:   m=pow(2,cptcoveff);
                   12496:  
1.144     brouard  12497:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12498:           * For k=4 covariates, h goes from 1 to m=2**k
                   12499:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12500:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12501:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12502:           *______________________________   *______________________
                   12503:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12504:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12505:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12506:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12507:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12508:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12509:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12510:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12511:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12512:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12513:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12514:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12515:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12516:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12517:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12518:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12519:           */                                     
1.212     brouard  12520:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12521:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12522:      * and the value of each covariate?
                   12523:      * V1=1, V2=1, V3=2, V4=1 ?
                   12524:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12525:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12526:      * In order to get the real value in the data, we use nbcode
                   12527:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12528:      * We are keeping this crazy system in order to be able (in the future?) 
                   12529:      * to have more than 2 values (0 or 1) for a covariate.
                   12530:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12531:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12532:      *              bbbbbbbb
                   12533:      *              76543210     
                   12534:      *   h-1        00000101 (6-1=5)
1.219     brouard  12535:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12536:      *           &
                   12537:      *     1        00000001 (1)
1.219     brouard  12538:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12539:      *          +1= 00000001 =1 
1.211     brouard  12540:      *
                   12541:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12542:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12543:      *    >>k'            11
                   12544:      *          &   00000001
                   12545:      *            = 00000001
                   12546:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12547:      * Reverse h=6 and m=16?
                   12548:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12549:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12550:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12551:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12552:      * V3=decodtabm(14,3,2**4)=2
                   12553:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12554:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12555:      *          &1 000000001
                   12556:      *           = 000000001
                   12557:      *         +1= 000000010 =2
                   12558:      *                  2211
                   12559:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12560:      *                  V3=2
1.220     brouard  12561:                 * codtabm and decodtabm are identical
1.211     brouard  12562:      */
                   12563: 
1.145     brouard  12564: 
                   12565:  free_ivector(Ndum,-1,NCOVMAX);
                   12566: 
                   12567: 
1.126     brouard  12568:     
1.186     brouard  12569:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12570:   strcpy(optionfilegnuplot,optionfilefiname);
                   12571:   if(mle==-3)
1.201     brouard  12572:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12573:   strcat(optionfilegnuplot,".gp");
                   12574: 
                   12575:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12576:     printf("Problem with file %s",optionfilegnuplot);
                   12577:   }
                   12578:   else{
1.204     brouard  12579:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12580:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12581:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12582:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12583:   }
                   12584:   /*  fclose(ficgp);*/
1.186     brouard  12585: 
                   12586: 
                   12587:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12588: 
                   12589:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12590:   if(mle==-3)
1.201     brouard  12591:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12592:   strcat(optionfilehtm,".htm");
                   12593:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12594:     printf("Problem with %s \n",optionfilehtm);
                   12595:     exit(0);
1.126     brouard  12596:   }
                   12597: 
                   12598:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12599:   strcat(optionfilehtmcov,"-cov.htm");
                   12600:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12601:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12602:   }
                   12603:   else{
                   12604:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12605: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12606: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12607:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12608:   }
                   12609: 
1.332     brouard  12610:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br>  \
1.204     brouard  12611: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12612: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12613: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12614: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12615: \n\
                   12616: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12617:  <ul><li><h4>Parameter files</h4>\n\
                   12618:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12619:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12620:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12621:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12622:  - Date and time at start: %s</ul>\n",\
                   12623:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12624:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12625:          fileres,fileres,\
                   12626:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12627:   fflush(fichtm);
                   12628: 
                   12629:   strcpy(pathr,path);
                   12630:   strcat(pathr,optionfilefiname);
1.184     brouard  12631: #ifdef WIN32
                   12632:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12633: #else
1.126     brouard  12634:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12635: #endif
                   12636:          
1.126     brouard  12637:   
1.220     brouard  12638:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12639:                 and for any valid combination of covariates
1.126     brouard  12640:      and prints on file fileres'p'. */
1.251     brouard  12641:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12642:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12643: 
                   12644:   fprintf(fichtm,"\n");
1.286     brouard  12645:   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  12646:          ftol, stepm);
                   12647:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12648:   ncurrv=1;
                   12649:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12650:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12651:   ncurrv=i;
                   12652:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12653:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12654:   ncurrv=i;
                   12655:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12656:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12657:   ncurrv=i;
                   12658:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12659:   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", \
                   12660:           nlstate, ndeath, maxwav, mle, weightopt);
                   12661: 
                   12662:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12663: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12664: 
                   12665:   
1.317     brouard  12666:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12667: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12668: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12669:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12670:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12671:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12672:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12673:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12674:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12675: 
1.126     brouard  12676:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12677:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12678:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12679: 
                   12680:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12681:   /* For mortality only */
1.126     brouard  12682:   if (mle==-3){
1.136     brouard  12683:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12684:     for(i=1;i<=NDIM;i++)
                   12685:       for(j=1;j<=NDIM;j++)
                   12686:        ximort[i][j]=0.;
1.186     brouard  12687:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12688:     cens=ivector(firstobs,lastobs);
                   12689:     ageexmed=vector(firstobs,lastobs);
                   12690:     agecens=vector(firstobs,lastobs);
                   12691:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12692:                
1.126     brouard  12693:     for (i=1; i<=imx; i++){
                   12694:       dcwave[i]=-1;
                   12695:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12696:        if (s[m][i]>nlstate) {
                   12697:          dcwave[i]=m;
                   12698:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12699:          break;
                   12700:        }
1.126     brouard  12701:     }
1.226     brouard  12702:     
1.126     brouard  12703:     for (i=1; i<=imx; i++) {
                   12704:       if (wav[i]>0){
1.226     brouard  12705:        ageexmed[i]=agev[mw[1][i]][i];
                   12706:        j=wav[i];
                   12707:        agecens[i]=1.; 
                   12708:        
                   12709:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12710:          agecens[i]=agev[mw[j][i]][i];
                   12711:          cens[i]= 1;
                   12712:        }else if (ageexmed[i]< 1) 
                   12713:          cens[i]= -1;
                   12714:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12715:          cens[i]=0 ;
1.126     brouard  12716:       }
                   12717:       else cens[i]=-1;
                   12718:     }
                   12719:     
                   12720:     for (i=1;i<=NDIM;i++) {
                   12721:       for (j=1;j<=NDIM;j++)
1.226     brouard  12722:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12723:     }
                   12724:     
1.302     brouard  12725:     p[1]=0.0268; p[NDIM]=0.083;
                   12726:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12727:     
                   12728:     
1.136     brouard  12729: #ifdef GSL
                   12730:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12731: #else
1.126     brouard  12732:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12733: #endif
1.201     brouard  12734:     strcpy(filerespow,"POW-MORT_"); 
                   12735:     strcat(filerespow,fileresu);
1.126     brouard  12736:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12737:       printf("Problem with resultfile: %s\n", filerespow);
                   12738:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12739:     }
1.136     brouard  12740: #ifdef GSL
                   12741:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12742: #else
1.126     brouard  12743:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12744: #endif
1.126     brouard  12745:     /*  for (i=1;i<=nlstate;i++)
                   12746:        for(j=1;j<=nlstate+ndeath;j++)
                   12747:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12748:     */
                   12749:     fprintf(ficrespow,"\n");
1.136     brouard  12750: #ifdef GSL
                   12751:     /* gsl starts here */ 
                   12752:     T = gsl_multimin_fminimizer_nmsimplex;
                   12753:     gsl_multimin_fminimizer *sfm = NULL;
                   12754:     gsl_vector *ss, *x;
                   12755:     gsl_multimin_function minex_func;
                   12756: 
                   12757:     /* Initial vertex size vector */
                   12758:     ss = gsl_vector_alloc (NDIM);
                   12759:     
                   12760:     if (ss == NULL){
                   12761:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12762:     }
                   12763:     /* Set all step sizes to 1 */
                   12764:     gsl_vector_set_all (ss, 0.001);
                   12765: 
                   12766:     /* Starting point */
1.126     brouard  12767:     
1.136     brouard  12768:     x = gsl_vector_alloc (NDIM);
                   12769:     
                   12770:     if (x == NULL){
                   12771:       gsl_vector_free(ss);
                   12772:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12773:     }
                   12774:   
                   12775:     /* Initialize method and iterate */
                   12776:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12777:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12778:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12779:     gsl_vector_set(x, 0, p[1]);
                   12780:     gsl_vector_set(x, 1, p[2]);
                   12781: 
                   12782:     minex_func.f = &gompertz_f;
                   12783:     minex_func.n = NDIM;
                   12784:     minex_func.params = (void *)&p; /* ??? */
                   12785:     
                   12786:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12787:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12788:     
                   12789:     printf("Iterations beginning .....\n\n");
                   12790:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12791: 
                   12792:     iteri=0;
                   12793:     while (rval == GSL_CONTINUE){
                   12794:       iteri++;
                   12795:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12796:       
                   12797:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12798:       fflush(0);
                   12799:       
                   12800:       if (status) 
                   12801:         break;
                   12802:       
                   12803:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12804:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12805:       
                   12806:       if (rval == GSL_SUCCESS)
                   12807:         printf ("converged to a local maximum at\n");
                   12808:       
                   12809:       printf("%5d ", iteri);
                   12810:       for (it = 0; it < NDIM; it++){
                   12811:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12812:       }
                   12813:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12814:     }
                   12815:     
                   12816:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12817:     
                   12818:     gsl_vector_free(x); /* initial values */
                   12819:     gsl_vector_free(ss); /* inital step size */
                   12820:     for (it=0; it<NDIM; it++){
                   12821:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12822:       fprintf(ficrespow," %.12lf", p[it]);
                   12823:     }
                   12824:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12825: #endif
                   12826: #ifdef POWELL
                   12827:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12828: #endif  
1.126     brouard  12829:     fclose(ficrespow);
                   12830:     
1.203     brouard  12831:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12832: 
                   12833:     for(i=1; i <=NDIM; i++)
                   12834:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12835:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12836:     
                   12837:     printf("\nCovariance matrix\n ");
1.203     brouard  12838:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12839:     for(i=1; i <=NDIM; i++) {
                   12840:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12841:                                printf("%f ",matcov[i][j]);
                   12842:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12843:       }
1.203     brouard  12844:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12845:     }
                   12846:     
                   12847:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12848:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12849:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12850:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12851:     }
1.302     brouard  12852:     lsurv=vector(agegomp,AGESUP);
                   12853:     lpop=vector(agegomp,AGESUP);
                   12854:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12855:     lsurv[agegomp]=100000;
                   12856:     
                   12857:     for (k=agegomp;k<=AGESUP;k++) {
                   12858:       agemortsup=k;
                   12859:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12860:     }
                   12861:     
                   12862:     for (k=agegomp;k<agemortsup;k++)
                   12863:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12864:     
                   12865:     for (k=agegomp;k<agemortsup;k++){
                   12866:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12867:       sumlpop=sumlpop+lpop[k];
                   12868:     }
                   12869:     
                   12870:     tpop[agegomp]=sumlpop;
                   12871:     for (k=agegomp;k<(agemortsup-3);k++){
                   12872:       /*  tpop[k+1]=2;*/
                   12873:       tpop[k+1]=tpop[k]-lpop[k];
                   12874:     }
                   12875:     
                   12876:     
                   12877:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12878:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12879:       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]);
                   12880:     
                   12881:     
                   12882:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12883:                ageminpar=50;
                   12884:                agemaxpar=100;
1.194     brouard  12885:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12886:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12887: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12888: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12889:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12890: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12891: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12892:     }else{
                   12893:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12894:                        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  12895:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12896:                }
1.201     brouard  12897:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12898:                     stepm, weightopt,\
                   12899:                     model,imx,p,matcov,agemortsup);
                   12900:     
1.302     brouard  12901:     free_vector(lsurv,agegomp,AGESUP);
                   12902:     free_vector(lpop,agegomp,AGESUP);
                   12903:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12904:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12905:     free_ivector(dcwave,firstobs,lastobs);
                   12906:     free_vector(agecens,firstobs,lastobs);
                   12907:     free_vector(ageexmed,firstobs,lastobs);
                   12908:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12909: #ifdef GSL
1.136     brouard  12910: #endif
1.186     brouard  12911:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12912:   /* Standard  */
                   12913:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12914:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12915:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12916:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12917:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12918:     for (k=1; k<=npar;k++)
                   12919:       printf(" %d %8.5f",k,p[k]);
                   12920:     printf("\n");
1.205     brouard  12921:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12922:       /* mlikeli uses func not funcone */
1.247     brouard  12923:       /* for(i=1;i<nlstate;i++){ */
                   12924:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12925:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12926:       /* } */
1.205     brouard  12927:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12928:     }
                   12929:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12930:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12931:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12932:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12933:     }
                   12934:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12935:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12936:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12937:     for (k=1; k<=npar;k++)
                   12938:       printf(" %d %8.5f",k,p[k]);
                   12939:     printf("\n");
                   12940:     
                   12941:     /*--------- results files --------------*/
1.283     brouard  12942:     /* 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  12943:     
                   12944:     
                   12945:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12946:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  12947:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12948: 
                   12949:     printf("#model=  1      +     age ");
                   12950:     fprintf(ficres,"#model=  1      +     age ");
                   12951:     fprintf(ficlog,"#model=  1      +     age ");
                   12952:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   12953: </ul>", model);
                   12954: 
                   12955:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   12956:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12957:     if(nagesqr==1){
                   12958:       printf("  + age*age  ");
                   12959:       fprintf(ficres,"  + age*age  ");
                   12960:       fprintf(ficlog,"  + age*age  ");
                   12961:       fprintf(fichtm, "<th>+ age*age</th>");
                   12962:     }
                   12963:     for(j=1;j <=ncovmodel-2;j++){
                   12964:       if(Typevar[j]==0) {
                   12965:        printf("  +      V%d  ",Tvar[j]);
                   12966:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   12967:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   12968:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12969:       }else if(Typevar[j]==1) {
                   12970:        printf("  +    V%d*age ",Tvar[j]);
                   12971:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   12972:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   12973:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12974:       }else if(Typevar[j]==2) {
                   12975:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12976:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12977:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12978:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12979:       }
                   12980:     }
                   12981:     printf("\n");
                   12982:     fprintf(ficres,"\n");
                   12983:     fprintf(ficlog,"\n");
                   12984:     fprintf(fichtm, "</tr>");
                   12985:     fprintf(fichtm, "\n");
                   12986:     
                   12987:     
1.126     brouard  12988:     for(i=1,jk=1; i <=nlstate; i++){
                   12989:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12990:        if (k != i) {
1.319     brouard  12991:          fprintf(fichtm, "<tr>");
1.225     brouard  12992:          printf("%d%d ",i,k);
                   12993:          fprintf(ficlog,"%d%d ",i,k);
                   12994:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  12995:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12996:          for(j=1; j <=ncovmodel; j++){
                   12997:            printf("%12.7f ",p[jk]);
                   12998:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12999:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13000:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13001:            jk++; 
                   13002:          }
                   13003:          printf("\n");
                   13004:          fprintf(ficlog,"\n");
                   13005:          fprintf(ficres,"\n");
1.319     brouard  13006:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13007:        }
1.126     brouard  13008:       }
                   13009:     }
1.319     brouard  13010:     /* fprintf(fichtm,"</tr>\n"); */
                   13011:     fprintf(fichtm,"</table>\n");
                   13012:     fprintf(fichtm, "\n");
                   13013: 
1.203     brouard  13014:     if(mle != 0){
                   13015:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13016:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13017:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13018:       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");
                   13019:       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  13020:       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  13021:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13022:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13023:       if(nagesqr==1){
                   13024:        printf("  + age*age  ");
                   13025:        fprintf(ficres,"  + age*age  ");
                   13026:        fprintf(ficlog,"  + age*age  ");
                   13027:        fprintf(fichtm, "<th>+ age*age</th>");
                   13028:       }
                   13029:       for(j=1;j <=ncovmodel-2;j++){
                   13030:        if(Typevar[j]==0) {
                   13031:          printf("  +      V%d  ",Tvar[j]);
                   13032:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13033:        }else if(Typevar[j]==1) {
                   13034:          printf("  +    V%d*age ",Tvar[j]);
                   13035:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13036:        }else if(Typevar[j]==2) {
                   13037:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13038:        }
                   13039:       }
                   13040:       fprintf(fichtm, "</tr>\n");
                   13041:  
1.203     brouard  13042:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13043:        for(k=1; k <=(nlstate+ndeath); k++){
                   13044:          if (k != i) {
1.319     brouard  13045:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13046:            printf("%d%d ",i,k);
                   13047:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13048:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13049:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13050:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13051:              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]));
                   13052:              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  13053:              if(fabs(wald) > 1.96){
1.321     brouard  13054:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13055:              }else{
                   13056:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13057:              }
1.324     brouard  13058:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13059:              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  13060:              jk++; 
                   13061:            }
                   13062:            printf("\n");
                   13063:            fprintf(ficlog,"\n");
1.319     brouard  13064:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13065:          }
                   13066:        }
1.193     brouard  13067:       }
1.203     brouard  13068:     } /* end of hesscov and Wald tests */
1.319     brouard  13069:     fprintf(fichtm,"</table>\n");
1.225     brouard  13070:     
1.203     brouard  13071:     /*  */
1.126     brouard  13072:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13073:     printf("# Scales (for hessian or gradient estimation)\n");
                   13074:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13075:     for(i=1,jk=1; i <=nlstate; i++){
                   13076:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13077:        if (j!=i) {
                   13078:          fprintf(ficres,"%1d%1d",i,j);
                   13079:          printf("%1d%1d",i,j);
                   13080:          fprintf(ficlog,"%1d%1d",i,j);
                   13081:          for(k=1; k<=ncovmodel;k++){
                   13082:            printf(" %.5e",delti[jk]);
                   13083:            fprintf(ficlog," %.5e",delti[jk]);
                   13084:            fprintf(ficres," %.5e",delti[jk]);
                   13085:            jk++;
                   13086:          }
                   13087:          printf("\n");
                   13088:          fprintf(ficlog,"\n");
                   13089:          fprintf(ficres,"\n");
                   13090:        }
1.126     brouard  13091:       }
                   13092:     }
                   13093:     
                   13094:     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  13095:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13096:       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");
                   13097:     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");
                   13098:     /* # 121 Var(a12)\n\ */
                   13099:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13100:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13101:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13102:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13103:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13104:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13105:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13106:     
                   13107:     
                   13108:     /* Just to have a covariance matrix which will be more understandable
                   13109:        even is we still don't want to manage dictionary of variables
                   13110:     */
                   13111:     for(itimes=1;itimes<=2;itimes++){
                   13112:       jj=0;
                   13113:       for(i=1; i <=nlstate; i++){
1.225     brouard  13114:        for(j=1; j <=nlstate+ndeath; j++){
                   13115:          if(j==i) continue;
                   13116:          for(k=1; k<=ncovmodel;k++){
                   13117:            jj++;
                   13118:            ca[0]= k+'a'-1;ca[1]='\0';
                   13119:            if(itimes==1){
                   13120:              if(mle>=1)
                   13121:                printf("#%1d%1d%d",i,j,k);
                   13122:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13123:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13124:            }else{
                   13125:              if(mle>=1)
                   13126:                printf("%1d%1d%d",i,j,k);
                   13127:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13128:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13129:            }
                   13130:            ll=0;
                   13131:            for(li=1;li <=nlstate; li++){
                   13132:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13133:                if(lj==li) continue;
                   13134:                for(lk=1;lk<=ncovmodel;lk++){
                   13135:                  ll++;
                   13136:                  if(ll<=jj){
                   13137:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13138:                    if(ll<jj){
                   13139:                      if(itimes==1){
                   13140:                        if(mle>=1)
                   13141:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13142:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13143:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13144:                      }else{
                   13145:                        if(mle>=1)
                   13146:                          printf(" %.5e",matcov[jj][ll]); 
                   13147:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13148:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13149:                      }
                   13150:                    }else{
                   13151:                      if(itimes==1){
                   13152:                        if(mle>=1)
                   13153:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13154:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13155:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13156:                      }else{
                   13157:                        if(mle>=1)
                   13158:                          printf(" %.7e",matcov[jj][ll]); 
                   13159:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13160:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13161:                      }
                   13162:                    }
                   13163:                  }
                   13164:                } /* end lk */
                   13165:              } /* end lj */
                   13166:            } /* end li */
                   13167:            if(mle>=1)
                   13168:              printf("\n");
                   13169:            fprintf(ficlog,"\n");
                   13170:            fprintf(ficres,"\n");
                   13171:            numlinepar++;
                   13172:          } /* end k*/
                   13173:        } /*end j */
1.126     brouard  13174:       } /* end i */
                   13175:     } /* end itimes */
                   13176:     
                   13177:     fflush(ficlog);
                   13178:     fflush(ficres);
1.225     brouard  13179:     while(fgets(line, MAXLINE, ficpar)) {
                   13180:       /* If line starts with a # it is a comment */
                   13181:       if (line[0] == '#') {
                   13182:        numlinepar++;
                   13183:        fputs(line,stdout);
                   13184:        fputs(line,ficparo);
                   13185:        fputs(line,ficlog);
1.299     brouard  13186:        fputs(line,ficres);
1.225     brouard  13187:        continue;
                   13188:       }else
                   13189:        break;
                   13190:     }
                   13191:     
1.209     brouard  13192:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13193:     /*   ungetc(c,ficpar); */
                   13194:     /*   fgets(line, MAXLINE, ficpar); */
                   13195:     /*   fputs(line,stdout); */
                   13196:     /*   fputs(line,ficparo); */
                   13197:     /* } */
                   13198:     /* ungetc(c,ficpar); */
1.126     brouard  13199:     
                   13200:     estepm=0;
1.209     brouard  13201:     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  13202:       
                   13203:       if (num_filled != 6) {
                   13204:        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);
                   13205:        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);
                   13206:        goto end;
                   13207:       }
                   13208:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13209:     }
                   13210:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13211:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13212:     
1.209     brouard  13213:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13214:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13215:     if (fage <= 2) {
                   13216:       bage = ageminpar;
                   13217:       fage = agemaxpar;
                   13218:     }
                   13219:     
                   13220:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13221:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13222:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13223:                
1.186     brouard  13224:     /* Other stuffs, more or less useful */    
1.254     brouard  13225:     while(fgets(line, MAXLINE, ficpar)) {
                   13226:       /* If line starts with a # it is a comment */
                   13227:       if (line[0] == '#') {
                   13228:        numlinepar++;
                   13229:        fputs(line,stdout);
                   13230:        fputs(line,ficparo);
                   13231:        fputs(line,ficlog);
1.299     brouard  13232:        fputs(line,ficres);
1.254     brouard  13233:        continue;
                   13234:       }else
                   13235:        break;
                   13236:     }
                   13237: 
                   13238:     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){
                   13239:       
                   13240:       if (num_filled != 7) {
                   13241:        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);
                   13242:        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);
                   13243:        goto end;
                   13244:       }
                   13245:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13246:       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);
                   13247:       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);
                   13248:       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  13249:     }
1.254     brouard  13250: 
                   13251:     while(fgets(line, MAXLINE, ficpar)) {
                   13252:       /* If line starts with a # it is a comment */
                   13253:       if (line[0] == '#') {
                   13254:        numlinepar++;
                   13255:        fputs(line,stdout);
                   13256:        fputs(line,ficparo);
                   13257:        fputs(line,ficlog);
1.299     brouard  13258:        fputs(line,ficres);
1.254     brouard  13259:        continue;
                   13260:       }else
                   13261:        break;
1.126     brouard  13262:     }
                   13263:     
                   13264:     
                   13265:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13266:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13267:     
1.254     brouard  13268:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13269:       if (num_filled != 1) {
                   13270:        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);
                   13271:        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);
                   13272:        goto end;
                   13273:       }
                   13274:       printf("pop_based=%d\n",popbased);
                   13275:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13276:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13277:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13278:     }
                   13279:      
1.258     brouard  13280:     /* Results */
1.332     brouard  13281:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13282:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13283:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13284:     endishere=0;
1.258     brouard  13285:     nresult=0;
1.308     brouard  13286:     parameterline=0;
1.258     brouard  13287:     do{
                   13288:       if(!fgets(line, MAXLINE, ficpar)){
                   13289:        endishere=1;
1.308     brouard  13290:        parameterline=15;
1.258     brouard  13291:       }else if (line[0] == '#') {
                   13292:        /* If line starts with a # it is a comment */
1.254     brouard  13293:        numlinepar++;
                   13294:        fputs(line,stdout);
                   13295:        fputs(line,ficparo);
                   13296:        fputs(line,ficlog);
1.299     brouard  13297:        fputs(line,ficres);
1.254     brouard  13298:        continue;
1.258     brouard  13299:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13300:        parameterline=11;
1.296     brouard  13301:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13302:        parameterline=12;
1.307     brouard  13303:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13304:        parameterline=13;
1.307     brouard  13305:       }
1.258     brouard  13306:       else{
                   13307:        parameterline=14;
1.254     brouard  13308:       }
1.308     brouard  13309:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13310:       case 11:
1.296     brouard  13311:        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)){
                   13312:                  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  13313:          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);
                   13314:          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);
                   13315:          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);
                   13316:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13317:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13318:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13319:           prvforecast = 1;
                   13320:        } 
                   13321:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13322:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13323:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13324:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13325:           prvforecast = 2;
                   13326:        }
                   13327:        else {
                   13328:          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);
                   13329:          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);
                   13330:          goto end;
1.258     brouard  13331:        }
1.254     brouard  13332:        break;
1.258     brouard  13333:       case 12:
1.296     brouard  13334:        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)){
                   13335:           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);
                   13336:          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);
                   13337:          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);
                   13338:          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);
                   13339:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13340:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13341:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13342:           prvbackcast = 1;
                   13343:        } 
                   13344:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13345:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13346:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13347:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13348:           prvbackcast = 2;
                   13349:        }
                   13350:        else {
                   13351:          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);
                   13352:          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);
                   13353:          goto end;
1.258     brouard  13354:        }
1.230     brouard  13355:        break;
1.258     brouard  13356:       case 13:
1.332     brouard  13357:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13358:        nresult++; /* Sum of resultlines */
1.332     brouard  13359:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13360:        /* removefirstspace(&resultlineori); */
                   13361:        
                   13362:        if(strstr(resultlineori,"v") !=0){
                   13363:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13364:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13365:          return 1;
                   13366:        }
                   13367:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13368:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13369:        if(nresult > MAXRESULTLINESPONE-1){
                   13370:          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);
                   13371:          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  13372:          goto end;
                   13373:        }
1.332     brouard  13374:        
1.310     brouard  13375:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13376:          fprintf(ficparo,"result: %s\n",resultline);
                   13377:          fprintf(ficres,"result: %s\n",resultline);
                   13378:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13379:        } else
                   13380:          goto end;
1.307     brouard  13381:        break;
                   13382:       case 14:
                   13383:        printf("Error: Unknown command '%s'\n",line);
                   13384:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13385:        if(line[0] == ' ' || line[0] == '\n'){
                   13386:          printf("It should not be an empty line '%s'\n",line);
                   13387:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13388:        }         
1.307     brouard  13389:        if(ncovmodel >=2 && nresult==0 ){
                   13390:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13391:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13392:        }
1.307     brouard  13393:        /* goto end; */
                   13394:        break;
1.308     brouard  13395:       case 15:
                   13396:        printf("End of resultlines.\n");
                   13397:        fprintf(ficlog,"End of resultlines.\n");
                   13398:        break;
                   13399:       default: /* parameterline =0 */
1.307     brouard  13400:        nresult=1;
                   13401:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13402:       } /* End switch parameterline */
                   13403:     }while(endishere==0); /* End do */
1.126     brouard  13404:     
1.230     brouard  13405:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13406:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13407:     
                   13408:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13409:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13410:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13411: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13412: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13413:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13414: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13415: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13416:     }else{
1.270     brouard  13417:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13418:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13419:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13420:       if(prvforecast==1){
                   13421:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13422:         jprojd=jproj1;
                   13423:         mprojd=mproj1;
                   13424:         anprojd=anproj1;
                   13425:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13426:         jprojf=jproj2;
                   13427:         mprojf=mproj2;
                   13428:         anprojf=anproj2;
                   13429:       } else if(prvforecast == 2){
                   13430:         dateprojd=dateintmean;
                   13431:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13432:         dateprojf=dateintmean+yrfproj;
                   13433:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13434:       }
                   13435:       if(prvbackcast==1){
                   13436:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13437:         jbackd=jback1;
                   13438:         mbackd=mback1;
                   13439:         anbackd=anback1;
                   13440:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13441:         jbackf=jback2;
                   13442:         mbackf=mback2;
                   13443:         anbackf=anback2;
                   13444:       } else if(prvbackcast == 2){
                   13445:         datebackd=dateintmean;
                   13446:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13447:         datebackf=dateintmean-yrbproj;
                   13448:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13449:       }
                   13450:       
                   13451:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13452:     }
                   13453:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13454:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13455:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13456:                
1.225     brouard  13457:     /*------------ free_vector  -------------*/
                   13458:     /*  chdir(path); */
1.220     brouard  13459:                
1.215     brouard  13460:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13461:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13462:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13463:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13464:     free_lvector(num,firstobs,lastobs);
                   13465:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13466:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13467:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13468:     fclose(ficparo);
                   13469:     fclose(ficres);
1.220     brouard  13470:                
                   13471:                
1.186     brouard  13472:     /* Other results (useful)*/
1.220     brouard  13473:                
                   13474:                
1.126     brouard  13475:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13476:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13477:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13478:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13479:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13480:     fclose(ficrespl);
                   13481: 
                   13482:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13483:     /*#include "hpijx.h"*/
1.332     brouard  13484:     /** 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?*/
                   13485:     /* calls hpxij with combination k */
1.180     brouard  13486:     hPijx(p, bage, fage);
1.145     brouard  13487:     fclose(ficrespij);
1.227     brouard  13488:     
1.220     brouard  13489:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13490:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13491:     k=1;
1.126     brouard  13492:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13493:     
1.269     brouard  13494:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13495:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13496:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13497:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13498:        for(k=1;k<=ncovcombmax;k++)
                   13499:          probs[i][j][k]=0.;
1.269     brouard  13500:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13501:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13502:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13503:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13504:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13505:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13506:          for(k=1;k<=ncovcombmax;k++)
                   13507:            mobaverages[i][j][k]=0.;
1.219     brouard  13508:       mobaverage=mobaverages;
                   13509:       if (mobilav!=0) {
1.235     brouard  13510:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13511:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13512:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13513:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13514:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13515:        }
1.269     brouard  13516:       } else if (mobilavproj !=0) {
1.235     brouard  13517:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13518:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13519:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13520:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13521:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13522:        }
1.269     brouard  13523:       }else{
                   13524:        printf("Internal error moving average\n");
                   13525:        fflush(stdout);
                   13526:        exit(1);
1.219     brouard  13527:       }
                   13528:     }/* end if moving average */
1.227     brouard  13529:     
1.126     brouard  13530:     /*---------- Forecasting ------------------*/
1.296     brouard  13531:     if(prevfcast==1){ 
                   13532:       /*   /\*    if(stepm ==1){*\/ */
                   13533:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13534:       /*This done previously after freqsummary.*/
                   13535:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13536:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13537:       
                   13538:       /* } else if (prvforecast==2){ */
                   13539:       /*   /\*    if(stepm ==1){*\/ */
                   13540:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13541:       /* } */
                   13542:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13543:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13544:     }
1.269     brouard  13545: 
1.296     brouard  13546:     /* Prevbcasting */
                   13547:     if(prevbcast==1){
1.219     brouard  13548:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13549:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13550:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13551: 
                   13552:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13553: 
                   13554:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13555: 
1.219     brouard  13556:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13557:       fclose(ficresplb);
                   13558: 
1.222     brouard  13559:       hBijx(p, bage, fage, mobaverage);
                   13560:       fclose(ficrespijb);
1.219     brouard  13561: 
1.296     brouard  13562:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13563:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13564:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13565:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13566:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13567:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13568: 
                   13569:       
1.269     brouard  13570:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13571: 
                   13572:       
1.269     brouard  13573:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13574:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13575:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13576:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13577:     }    /* end  Prevbcasting */
1.268     brouard  13578:  
1.186     brouard  13579:  
                   13580:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13581: 
1.215     brouard  13582:     free_ivector(wav,1,imx);
                   13583:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13584:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13585:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13586:                
                   13587:                
1.127     brouard  13588:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13589:                
1.201     brouard  13590:     strcpy(filerese,"E_");
                   13591:     strcat(filerese,fileresu);
1.126     brouard  13592:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13593:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13594:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13595:     }
1.208     brouard  13596:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13597:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13598: 
                   13599:     pstamp(ficreseij);
1.219     brouard  13600:                
1.235     brouard  13601:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13602:     if (cptcovn < 1){i1=1;}
                   13603:     
                   13604:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13605:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13606:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13607:        continue;
1.219     brouard  13608:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13609:       printf("\n#****** ");
1.225     brouard  13610:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  13611:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13612:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  13613:       }
                   13614:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  13615:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   13616:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.219     brouard  13617:       }
                   13618:       fprintf(ficreseij,"******\n");
1.235     brouard  13619:       printf("******\n");
1.219     brouard  13620:       
                   13621:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13622:       oldm=oldms;savm=savms;
1.330     brouard  13623:       /* 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  13624:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13625:       
1.219     brouard  13626:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13627:     }
                   13628:     fclose(ficreseij);
1.208     brouard  13629:     printf("done evsij\n");fflush(stdout);
                   13630:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13631: 
1.218     brouard  13632:                
1.227     brouard  13633:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13634:                
1.201     brouard  13635:     strcpy(filerest,"T_");
                   13636:     strcat(filerest,fileresu);
1.127     brouard  13637:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13638:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13639:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13640:     }
1.208     brouard  13641:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13642:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13643:     strcpy(fileresstde,"STDE_");
                   13644:     strcat(fileresstde,fileresu);
1.126     brouard  13645:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13646:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13647:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13648:     }
1.227     brouard  13649:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13650:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13651: 
1.201     brouard  13652:     strcpy(filerescve,"CVE_");
                   13653:     strcat(filerescve,fileresu);
1.126     brouard  13654:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13655:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13656:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13657:     }
1.227     brouard  13658:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13659:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13660: 
1.201     brouard  13661:     strcpy(fileresv,"V_");
                   13662:     strcat(fileresv,fileresu);
1.126     brouard  13663:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13664:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13665:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13666:     }
1.227     brouard  13667:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13668:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13669: 
1.235     brouard  13670:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13671:     if (cptcovn < 1){i1=1;}
                   13672:     
                   13673:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13674:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13675:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13676:        continue;
1.321     brouard  13677:       printf("\n# model %s \n#****** Result for:", model);
                   13678:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13679:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.227     brouard  13680:       for(j=1;j<=cptcoveff;j++){ 
1.332     brouard  13681:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13682:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13683:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  13684:       }
1.235     brouard  13685:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  13686:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   13687:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   13688:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.235     brouard  13689:       }        
1.208     brouard  13690:       fprintf(ficrest,"******\n");
1.227     brouard  13691:       fprintf(ficlog,"******\n");
                   13692:       printf("******\n");
1.208     brouard  13693:       
                   13694:       fprintf(ficresstdeij,"\n#****** ");
                   13695:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13696:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  13697:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13698:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.208     brouard  13699:       }
1.235     brouard  13700:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  13701:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   13702:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.235     brouard  13703:       }        
1.208     brouard  13704:       fprintf(ficresstdeij,"******\n");
                   13705:       fprintf(ficrescveij,"******\n");
                   13706:       
                   13707:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13708:       /* pstamp(ficresvij); */
1.225     brouard  13709:       for(j=1;j<=cptcoveff;j++) 
1.332     brouard  13710:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]);
1.235     brouard  13711:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  13712:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
                   13713:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  13714:       }        
1.208     brouard  13715:       fprintf(ficresvij,"******\n");
                   13716:       
                   13717:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13718:       oldm=oldms;savm=savms;
1.235     brouard  13719:       printf(" cvevsij ");
                   13720:       fprintf(ficlog, " cvevsij ");
                   13721:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13722:       printf(" end cvevsij \n ");
                   13723:       fprintf(ficlog, " end cvevsij \n ");
                   13724:       
                   13725:       /*
                   13726:        */
                   13727:       /* goto endfree; */
                   13728:       
                   13729:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13730:       pstamp(ficrest);
                   13731:       
1.269     brouard  13732:       epj=vector(1,nlstate+1);
1.208     brouard  13733:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13734:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13735:        cptcod= 0; /* To be deleted */
                   13736:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13737:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13738:        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  13739:        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 ");
                   13740:        if(vpopbased==1)
                   13741:          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);
                   13742:        else
1.288     brouard  13743:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13744:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13745:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13746:        fprintf(ficrest,"\n");
                   13747:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13748:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13749:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13750:        for(age=bage; age <=fage ;age++){
1.235     brouard  13751:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13752:          if (vpopbased==1) {
                   13753:            if(mobilav ==0){
                   13754:              for(i=1; i<=nlstate;i++)
                   13755:                prlim[i][i]=probs[(int)age][i][k];
                   13756:            }else{ /* mobilav */ 
                   13757:              for(i=1; i<=nlstate;i++)
                   13758:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13759:            }
                   13760:          }
1.219     brouard  13761:          
1.227     brouard  13762:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13763:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13764:          /* printf(" age %4.0f ",age); */
                   13765:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13766:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13767:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13768:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13769:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13770:            }
                   13771:            epj[nlstate+1] +=epj[j];
                   13772:          }
                   13773:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13774:          
1.227     brouard  13775:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13776:            for(j=1;j <=nlstate;j++)
                   13777:              vepp += vareij[i][j][(int)age];
                   13778:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13779:          for(j=1;j <=nlstate;j++){
                   13780:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13781:          }
                   13782:          fprintf(ficrest,"\n");
                   13783:        }
1.208     brouard  13784:       } /* End vpopbased */
1.269     brouard  13785:       free_vector(epj,1,nlstate+1);
1.208     brouard  13786:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13787:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13788:       printf("done selection\n");fflush(stdout);
                   13789:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13790:       
1.235     brouard  13791:     } /* End k selection */
1.227     brouard  13792: 
                   13793:     printf("done State-specific expectancies\n");fflush(stdout);
                   13794:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13795: 
1.288     brouard  13796:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13797:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13798: 
1.227     brouard  13799:     
1.290     brouard  13800:     free_vector(weight,firstobs,lastobs);
1.330     brouard  13801:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  13802:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13803:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13804:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13805:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13806:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13807:     free_ivector(tab,1,NCOVMAX);
                   13808:     fclose(ficresstdeij);
                   13809:     fclose(ficrescveij);
                   13810:     fclose(ficresvij);
                   13811:     fclose(ficrest);
                   13812:     fclose(ficpar);
                   13813:     
                   13814:     
1.126     brouard  13815:     /*---------- End : free ----------------*/
1.219     brouard  13816:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13817:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13818:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13819:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13820:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13821:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13822:   /* endfree:*/
                   13823:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13824:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13825:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13826:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13827:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13828:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13829:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13830:   free_matrix(matcov,1,npar,1,npar);
                   13831:   free_matrix(hess,1,npar,1,npar);
                   13832:   /*free_vector(delti,1,npar);*/
                   13833:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13834:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13835:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13836:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13837:   
                   13838:   free_ivector(ncodemax,1,NCOVMAX);
                   13839:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13840:   free_ivector(Dummy,-1,NCOVMAX);
                   13841:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13842:   free_ivector(DummyV,1,NCOVMAX);
                   13843:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13844:   free_ivector(Typevar,-1,NCOVMAX);
                   13845:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13846:   free_ivector(TvarsQ,1,NCOVMAX);
                   13847:   free_ivector(TvarsQind,1,NCOVMAX);
                   13848:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  13849:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  13850:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13851:   free_ivector(TvarFD,1,NCOVMAX);
                   13852:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13853:   free_ivector(TvarF,1,NCOVMAX);
                   13854:   free_ivector(TvarFind,1,NCOVMAX);
                   13855:   free_ivector(TvarV,1,NCOVMAX);
                   13856:   free_ivector(TvarVind,1,NCOVMAX);
                   13857:   free_ivector(TvarA,1,NCOVMAX);
                   13858:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13859:   free_ivector(TvarFQ,1,NCOVMAX);
                   13860:   free_ivector(TvarFQind,1,NCOVMAX);
                   13861:   free_ivector(TvarVD,1,NCOVMAX);
                   13862:   free_ivector(TvarVDind,1,NCOVMAX);
                   13863:   free_ivector(TvarVQ,1,NCOVMAX);
                   13864:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13865:   free_ivector(Tvarsel,1,NCOVMAX);
                   13866:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13867:   free_ivector(Tposprod,1,NCOVMAX);
                   13868:   free_ivector(Tprod,1,NCOVMAX);
                   13869:   free_ivector(Tvaraff,1,NCOVMAX);
                   13870:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13871:   free_ivector(Tage,1,NCOVMAX);
                   13872:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13873:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13874:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  13875: 
                   13876:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   13877: 
1.227     brouard  13878:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13879:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13880:   fflush(fichtm);
                   13881:   fflush(ficgp);
                   13882:   
1.227     brouard  13883:   
1.126     brouard  13884:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13885:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13886:     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  13887:   }else{
                   13888:     printf("End of Imach\n");
                   13889:     fprintf(ficlog,"End of Imach\n");
                   13890:   }
                   13891:   printf("See log file on %s\n",filelog);
                   13892:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13893:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13894:   rend_time = time(NULL);  
                   13895:   end_time = *localtime(&rend_time);
                   13896:   /* tml = *localtime(&end_time.tm_sec); */
                   13897:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13898:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13899:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13900:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13901:   
1.157     brouard  13902:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13903:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13904:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13905:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13906: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13907:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13908:   fclose(fichtm);
                   13909:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13910:   fclose(fichtmcov);
                   13911:   fclose(ficgp);
                   13912:   fclose(ficlog);
                   13913:   /*------ End -----------*/
1.227     brouard  13914:   
1.281     brouard  13915: 
                   13916: /* Executes gnuplot */
1.227     brouard  13917:   
                   13918:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13919: #ifdef WIN32
1.227     brouard  13920:   if (_chdir(pathcd) != 0)
                   13921:     printf("Can't move to directory %s!\n",path);
                   13922:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13923: #else
1.227     brouard  13924:     if(chdir(pathcd) != 0)
                   13925:       printf("Can't move to directory %s!\n", path);
                   13926:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13927: #endif 
1.126     brouard  13928:     printf("Current directory %s!\n",pathcd);
                   13929:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13930:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13931: #ifdef _WIN32
1.126     brouard  13932:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13933: #endif
                   13934:   if(!stat(plotcmd,&info)){
1.158     brouard  13935:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13936:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13937:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13938:     }else
                   13939:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13940: #ifdef __unix
1.126     brouard  13941:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13942:     if(!stat(plotcmd,&info)){
1.158     brouard  13943:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13944:     }else
                   13945:       strcpy(pplotcmd,plotcmd);
                   13946: #endif
                   13947:   }else
                   13948:     strcpy(pplotcmd,plotcmd);
                   13949:   
                   13950:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13951:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13952:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13953:   
1.126     brouard  13954:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13955:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13956:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13957:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13958:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13959:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13960:       strcpy(plotcmd,pplotcmd);
                   13961:     }
1.126     brouard  13962:   }
1.158     brouard  13963:   printf(" Successful, please wait...");
1.126     brouard  13964:   while (z[0] != 'q') {
                   13965:     /* chdir(path); */
1.154     brouard  13966:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13967:     scanf("%s",z);
                   13968: /*     if (z[0] == 'c') system("./imach"); */
                   13969:     if (z[0] == 'e') {
1.158     brouard  13970: #ifdef __APPLE__
1.152     brouard  13971:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13972: #elif __linux
                   13973:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13974: #else
1.152     brouard  13975:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13976: #endif
                   13977:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13978:       system(pplotcmd);
1.126     brouard  13979:     }
                   13980:     else if (z[0] == 'g') system(plotcmd);
                   13981:     else if (z[0] == 'q') exit(0);
                   13982:   }
1.227     brouard  13983: end:
1.126     brouard  13984:   while (z[0] != 'q') {
1.195     brouard  13985:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13986:     scanf("%s",z);
                   13987:   }
1.283     brouard  13988:   printf("End\n");
1.282     brouard  13989:   exit(0);
1.126     brouard  13990: }

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