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

1.321   ! brouard     1: /* $Id: imach.c,v 1.320 2022/06/02 05:10:11 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.321   ! brouard     4:   Revision 1.320  2022/06/02 05:10:11  brouard
        !             5:   *** empty log message ***
        !             6: 
1.320     brouard     7:   Revision 1.319  2022/06/02 04:45:11  brouard
                      8:   * imach.c (Module): Adding the Wald tests from the log to the main
                      9:   htm for better display of the maximum likelihood estimators.
                     10: 
1.319     brouard    11:   Revision 1.318  2022/05/24 08:10:59  brouard
                     12:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     13:   of confidencce intervals with product in the equation modelC
                     14: 
1.318     brouard    15:   Revision 1.317  2022/05/15 15:06:23  brouard
                     16:   * imach.c (Module):  Some minor improvements
                     17: 
1.317     brouard    18:   Revision 1.316  2022/05/11 15:11:31  brouard
                     19:   Summary: r27
                     20: 
1.316     brouard    21:   Revision 1.315  2022/05/11 15:06:32  brouard
                     22:   *** empty log message ***
                     23: 
1.315     brouard    24:   Revision 1.314  2022/04/13 17:43:09  brouard
                     25:   * imach.c (Module): Adding link to text data files
                     26: 
1.314     brouard    27:   Revision 1.313  2022/04/11 15:57:42  brouard
                     28:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     29: 
1.313     brouard    30:   Revision 1.312  2022/04/05 21:24:39  brouard
                     31:   *** empty log message ***
                     32: 
1.312     brouard    33:   Revision 1.311  2022/04/05 21:03:51  brouard
                     34:   Summary: Fixed quantitative covariates
                     35: 
                     36:          Fixed covariates (dummy or quantitative)
                     37:        with missing values have never been allowed but are ERRORS and
                     38:        program quits. Standard deviations of fixed covariates were
                     39:        wrongly computed. Mean and standard deviations of time varying
                     40:        covariates are still not computed.
                     41: 
1.311     brouard    42:   Revision 1.310  2022/03/17 08:45:53  brouard
                     43:   Summary: 99r25
                     44: 
                     45:   Improving detection of errors: result lines should be compatible with
                     46:   the model.
                     47: 
1.310     brouard    48:   Revision 1.309  2021/05/20 12:39:14  brouard
                     49:   Summary: Version 0.99r24
                     50: 
1.309     brouard    51:   Revision 1.308  2021/03/31 13:11:57  brouard
                     52:   Summary: Version 0.99r23
                     53: 
                     54: 
                     55:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     56: 
1.308     brouard    57:   Revision 1.307  2021/03/08 18:11:32  brouard
                     58:   Summary: 0.99r22 fixed bug on result:
                     59: 
1.307     brouard    60:   Revision 1.306  2021/02/20 15:44:02  brouard
                     61:   Summary: Version 0.99r21
                     62: 
                     63:   * imach.c (Module): Fix bug on quitting after result lines!
                     64:   (Module): Version 0.99r21
                     65: 
1.306     brouard    66:   Revision 1.305  2021/02/20 15:28:30  brouard
                     67:   * imach.c (Module): Fix bug on quitting after result lines!
                     68: 
1.305     brouard    69:   Revision 1.304  2021/02/12 11:34:20  brouard
                     70:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                     71: 
1.304     brouard    72:   Revision 1.303  2021/02/11 19:50:15  brouard
                     73:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                     74: 
1.303     brouard    75:   Revision 1.302  2020/02/22 21:00:05  brouard
                     76:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                     77:   and life table from the data without any state)
                     78: 
1.302     brouard    79:   Revision 1.301  2019/06/04 13:51:20  brouard
                     80:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                     81: 
1.301     brouard    82:   Revision 1.300  2019/05/22 19:09:45  brouard
                     83:   Summary: version 0.99r19 of May 2019
                     84: 
1.300     brouard    85:   Revision 1.299  2019/05/22 18:37:08  brouard
                     86:   Summary: Cleaned 0.99r19
                     87: 
1.299     brouard    88:   Revision 1.298  2019/05/22 18:19:56  brouard
                     89:   *** empty log message ***
                     90: 
1.298     brouard    91:   Revision 1.297  2019/05/22 17:56:10  brouard
                     92:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                     93: 
1.297     brouard    94:   Revision 1.296  2019/05/20 13:03:18  brouard
                     95:   Summary: Projection syntax simplified
                     96: 
                     97: 
                     98:   We can now start projections, forward or backward, from the mean date
                     99:   of inteviews up to or down to a number of years of projection:
                    100:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    101:   or
                    102:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    103:   or
                    104:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    105:   or
                    106:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    107: 
1.296     brouard   108:   Revision 1.295  2019/05/18 09:52:50  brouard
                    109:   Summary: doxygen tex bug
                    110: 
1.295     brouard   111:   Revision 1.294  2019/05/16 14:54:33  brouard
                    112:   Summary: There was some wrong lines added
                    113: 
1.294     brouard   114:   Revision 1.293  2019/05/09 15:17:34  brouard
                    115:   *** empty log message ***
                    116: 
1.293     brouard   117:   Revision 1.292  2019/05/09 14:17:20  brouard
                    118:   Summary: Some updates
                    119: 
1.292     brouard   120:   Revision 1.291  2019/05/09 13:44:18  brouard
                    121:   Summary: Before ncovmax
                    122: 
1.291     brouard   123:   Revision 1.290  2019/05/09 13:39:37  brouard
                    124:   Summary: 0.99r18 unlimited number of individuals
                    125: 
                    126:   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.
                    127: 
1.290     brouard   128:   Revision 1.289  2018/12/13 09:16:26  brouard
                    129:   Summary: Bug for young ages (<-30) will be in r17
                    130: 
1.289     brouard   131:   Revision 1.288  2018/05/02 20:58:27  brouard
                    132:   Summary: Some bugs fixed
                    133: 
1.288     brouard   134:   Revision 1.287  2018/05/01 17:57:25  brouard
                    135:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    136: 
1.287     brouard   137:   Revision 1.286  2018/04/27 14:27:04  brouard
                    138:   Summary: some minor bugs
                    139: 
1.286     brouard   140:   Revision 1.285  2018/04/21 21:02:16  brouard
                    141:   Summary: Some bugs fixed, valgrind tested
                    142: 
1.285     brouard   143:   Revision 1.284  2018/04/20 05:22:13  brouard
                    144:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    145: 
1.284     brouard   146:   Revision 1.283  2018/04/19 14:49:16  brouard
                    147:   Summary: Some minor bugs fixed
                    148: 
1.283     brouard   149:   Revision 1.282  2018/02/27 22:50:02  brouard
                    150:   *** empty log message ***
                    151: 
1.282     brouard   152:   Revision 1.281  2018/02/27 19:25:23  brouard
                    153:   Summary: Adding second argument for quitting
                    154: 
1.281     brouard   155:   Revision 1.280  2018/02/21 07:58:13  brouard
                    156:   Summary: 0.99r15
                    157: 
                    158:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    159: 
1.280     brouard   160:   Revision 1.279  2017/07/20 13:35:01  brouard
                    161:   Summary: temporary working
                    162: 
1.279     brouard   163:   Revision 1.278  2017/07/19 14:09:02  brouard
                    164:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    165: 
1.278     brouard   166:   Revision 1.277  2017/07/17 08:53:49  brouard
                    167:   Summary: BOM files can be read now
                    168: 
1.277     brouard   169:   Revision 1.276  2017/06/30 15:48:31  brouard
                    170:   Summary: Graphs improvements
                    171: 
1.276     brouard   172:   Revision 1.275  2017/06/30 13:39:33  brouard
                    173:   Summary: Saito's color
                    174: 
1.275     brouard   175:   Revision 1.274  2017/06/29 09:47:08  brouard
                    176:   Summary: Version 0.99r14
                    177: 
1.274     brouard   178:   Revision 1.273  2017/06/27 11:06:02  brouard
                    179:   Summary: More documentation on projections
                    180: 
1.273     brouard   181:   Revision 1.272  2017/06/27 10:22:40  brouard
                    182:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    183: 
1.272     brouard   184:   Revision 1.271  2017/06/27 10:17:50  brouard
                    185:   Summary: Some bug with rint
                    186: 
1.271     brouard   187:   Revision 1.270  2017/05/24 05:45:29  brouard
                    188:   *** empty log message ***
                    189: 
1.270     brouard   190:   Revision 1.269  2017/05/23 08:39:25  brouard
                    191:   Summary: Code into subroutine, cleanings
                    192: 
1.269     brouard   193:   Revision 1.268  2017/05/18 20:09:32  brouard
                    194:   Summary: backprojection and confidence intervals of backprevalence
                    195: 
1.268     brouard   196:   Revision 1.267  2017/05/13 10:25:05  brouard
                    197:   Summary: temporary save for backprojection
                    198: 
1.267     brouard   199:   Revision 1.266  2017/05/13 07:26:12  brouard
                    200:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    201: 
1.266     brouard   202:   Revision 1.265  2017/04/26 16:22:11  brouard
                    203:   Summary: imach 0.99r13 Some bugs fixed
                    204: 
1.265     brouard   205:   Revision 1.264  2017/04/26 06:01:29  brouard
                    206:   Summary: Labels in graphs
                    207: 
1.264     brouard   208:   Revision 1.263  2017/04/24 15:23:15  brouard
                    209:   Summary: to save
                    210: 
1.263     brouard   211:   Revision 1.262  2017/04/18 16:48:12  brouard
                    212:   *** empty log message ***
                    213: 
1.262     brouard   214:   Revision 1.261  2017/04/05 10:14:09  brouard
                    215:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    216: 
1.261     brouard   217:   Revision 1.260  2017/04/04 17:46:59  brouard
                    218:   Summary: Gnuplot indexations fixed (humm)
                    219: 
1.260     brouard   220:   Revision 1.259  2017/04/04 13:01:16  brouard
                    221:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    222: 
1.259     brouard   223:   Revision 1.258  2017/04/03 10:17:47  brouard
                    224:   Summary: Version 0.99r12
                    225: 
                    226:   Some cleanings, conformed with updated documentation.
                    227: 
1.258     brouard   228:   Revision 1.257  2017/03/29 16:53:30  brouard
                    229:   Summary: Temp
                    230: 
1.257     brouard   231:   Revision 1.256  2017/03/27 05:50:23  brouard
                    232:   Summary: Temporary
                    233: 
1.256     brouard   234:   Revision 1.255  2017/03/08 16:02:28  brouard
                    235:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    236: 
1.255     brouard   237:   Revision 1.254  2017/03/08 07:13:00  brouard
                    238:   Summary: Fixing data parameter line
                    239: 
1.254     brouard   240:   Revision 1.253  2016/12/15 11:59:41  brouard
                    241:   Summary: 0.99 in progress
                    242: 
1.253     brouard   243:   Revision 1.252  2016/09/15 21:15:37  brouard
                    244:   *** empty log message ***
                    245: 
1.252     brouard   246:   Revision 1.251  2016/09/15 15:01:13  brouard
                    247:   Summary: not working
                    248: 
1.251     brouard   249:   Revision 1.250  2016/09/08 16:07:27  brouard
                    250:   Summary: continue
                    251: 
1.250     brouard   252:   Revision 1.249  2016/09/07 17:14:18  brouard
                    253:   Summary: Starting values from frequencies
                    254: 
1.249     brouard   255:   Revision 1.248  2016/09/07 14:10:18  brouard
                    256:   *** empty log message ***
                    257: 
1.248     brouard   258:   Revision 1.247  2016/09/02 11:11:21  brouard
                    259:   *** empty log message ***
                    260: 
1.247     brouard   261:   Revision 1.246  2016/09/02 08:49:22  brouard
                    262:   *** empty log message ***
                    263: 
1.246     brouard   264:   Revision 1.245  2016/09/02 07:25:01  brouard
                    265:   *** empty log message ***
                    266: 
1.245     brouard   267:   Revision 1.244  2016/09/02 07:17:34  brouard
                    268:   *** empty log message ***
                    269: 
1.244     brouard   270:   Revision 1.243  2016/09/02 06:45:35  brouard
                    271:   *** empty log message ***
                    272: 
1.243     brouard   273:   Revision 1.242  2016/08/30 15:01:20  brouard
                    274:   Summary: Fixing a lots
                    275: 
1.242     brouard   276:   Revision 1.241  2016/08/29 17:17:25  brouard
                    277:   Summary: gnuplot problem in Back projection to fix
                    278: 
1.241     brouard   279:   Revision 1.240  2016/08/29 07:53:18  brouard
                    280:   Summary: Better
                    281: 
1.240     brouard   282:   Revision 1.239  2016/08/26 15:51:03  brouard
                    283:   Summary: Improvement in Powell output in order to copy and paste
                    284: 
                    285:   Author:
                    286: 
1.239     brouard   287:   Revision 1.238  2016/08/26 14:23:35  brouard
                    288:   Summary: Starting tests of 0.99
                    289: 
1.238     brouard   290:   Revision 1.237  2016/08/26 09:20:19  brouard
                    291:   Summary: to valgrind
                    292: 
1.237     brouard   293:   Revision 1.236  2016/08/25 10:50:18  brouard
                    294:   *** empty log message ***
                    295: 
1.236     brouard   296:   Revision 1.235  2016/08/25 06:59:23  brouard
                    297:   *** empty log message ***
                    298: 
1.235     brouard   299:   Revision 1.234  2016/08/23 16:51:20  brouard
                    300:   *** empty log message ***
                    301: 
1.234     brouard   302:   Revision 1.233  2016/08/23 07:40:50  brouard
                    303:   Summary: not working
                    304: 
1.233     brouard   305:   Revision 1.232  2016/08/22 14:20:21  brouard
                    306:   Summary: not working
                    307: 
1.232     brouard   308:   Revision 1.231  2016/08/22 07:17:15  brouard
                    309:   Summary: not working
                    310: 
1.231     brouard   311:   Revision 1.230  2016/08/22 06:55:53  brouard
                    312:   Summary: Not working
                    313: 
1.230     brouard   314:   Revision 1.229  2016/07/23 09:45:53  brouard
                    315:   Summary: Completing for func too
                    316: 
1.229     brouard   317:   Revision 1.228  2016/07/22 17:45:30  brouard
                    318:   Summary: Fixing some arrays, still debugging
                    319: 
1.227     brouard   320:   Revision 1.226  2016/07/12 18:42:34  brouard
                    321:   Summary: temp
                    322: 
1.226     brouard   323:   Revision 1.225  2016/07/12 08:40:03  brouard
                    324:   Summary: saving but not running
                    325: 
1.225     brouard   326:   Revision 1.224  2016/07/01 13:16:01  brouard
                    327:   Summary: Fixes
                    328: 
1.224     brouard   329:   Revision 1.223  2016/02/19 09:23:35  brouard
                    330:   Summary: temporary
                    331: 
1.223     brouard   332:   Revision 1.222  2016/02/17 08:14:50  brouard
                    333:   Summary: Probably last 0.98 stable version 0.98r6
                    334: 
1.222     brouard   335:   Revision 1.221  2016/02/15 23:35:36  brouard
                    336:   Summary: minor bug
                    337: 
1.220     brouard   338:   Revision 1.219  2016/02/15 00:48:12  brouard
                    339:   *** empty log message ***
                    340: 
1.219     brouard   341:   Revision 1.218  2016/02/12 11:29:23  brouard
                    342:   Summary: 0.99 Back projections
                    343: 
1.218     brouard   344:   Revision 1.217  2015/12/23 17:18:31  brouard
                    345:   Summary: Experimental backcast
                    346: 
1.217     brouard   347:   Revision 1.216  2015/12/18 17:32:11  brouard
                    348:   Summary: 0.98r4 Warning and status=-2
                    349: 
                    350:   Version 0.98r4 is now:
                    351:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    352:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    353:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    354: 
1.216     brouard   355:   Revision 1.215  2015/12/16 08:52:24  brouard
                    356:   Summary: 0.98r4 working
                    357: 
1.215     brouard   358:   Revision 1.214  2015/12/16 06:57:54  brouard
                    359:   Summary: temporary not working
                    360: 
1.214     brouard   361:   Revision 1.213  2015/12/11 18:22:17  brouard
                    362:   Summary: 0.98r4
                    363: 
1.213     brouard   364:   Revision 1.212  2015/11/21 12:47:24  brouard
                    365:   Summary: minor typo
                    366: 
1.212     brouard   367:   Revision 1.211  2015/11/21 12:41:11  brouard
                    368:   Summary: 0.98r3 with some graph of projected cross-sectional
                    369: 
                    370:   Author: Nicolas Brouard
                    371: 
1.211     brouard   372:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   373:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   374:   Summary: Adding ftolpl parameter
                    375:   Author: N Brouard
                    376: 
                    377:   We had difficulties to get smoothed confidence intervals. It was due
                    378:   to the period prevalence which wasn't computed accurately. The inner
                    379:   parameter ftolpl is now an outer parameter of the .imach parameter
                    380:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    381:   computation are long.
                    382: 
1.209     brouard   383:   Revision 1.208  2015/11/17 14:31:57  brouard
                    384:   Summary: temporary
                    385: 
1.208     brouard   386:   Revision 1.207  2015/10/27 17:36:57  brouard
                    387:   *** empty log message ***
                    388: 
1.207     brouard   389:   Revision 1.206  2015/10/24 07:14:11  brouard
                    390:   *** empty log message ***
                    391: 
1.206     brouard   392:   Revision 1.205  2015/10/23 15:50:53  brouard
                    393:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    394: 
1.205     brouard   395:   Revision 1.204  2015/10/01 16:20:26  brouard
                    396:   Summary: Some new graphs of contribution to likelihood
                    397: 
1.204     brouard   398:   Revision 1.203  2015/09/30 17:45:14  brouard
                    399:   Summary: looking at better estimation of the hessian
                    400: 
                    401:   Also a better criteria for convergence to the period prevalence And
                    402:   therefore adding the number of years needed to converge. (The
                    403:   prevalence in any alive state shold sum to one
                    404: 
1.203     brouard   405:   Revision 1.202  2015/09/22 19:45:16  brouard
                    406:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    407: 
1.202     brouard   408:   Revision 1.201  2015/09/15 17:34:58  brouard
                    409:   Summary: 0.98r0
                    410: 
                    411:   - Some new graphs like suvival functions
                    412:   - Some bugs fixed like model=1+age+V2.
                    413: 
1.201     brouard   414:   Revision 1.200  2015/09/09 16:53:55  brouard
                    415:   Summary: Big bug thanks to Flavia
                    416: 
                    417:   Even model=1+age+V2. did not work anymore
                    418: 
1.200     brouard   419:   Revision 1.199  2015/09/07 14:09:23  brouard
                    420:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    421: 
1.199     brouard   422:   Revision 1.198  2015/09/03 07:14:39  brouard
                    423:   Summary: 0.98q5 Flavia
                    424: 
1.198     brouard   425:   Revision 1.197  2015/09/01 18:24:39  brouard
                    426:   *** empty log message ***
                    427: 
1.197     brouard   428:   Revision 1.196  2015/08/18 23:17:52  brouard
                    429:   Summary: 0.98q5
                    430: 
1.196     brouard   431:   Revision 1.195  2015/08/18 16:28:39  brouard
                    432:   Summary: Adding a hack for testing purpose
                    433: 
                    434:   After reading the title, ftol and model lines, if the comment line has
                    435:   a q, starting with #q, the answer at the end of the run is quit. It
                    436:   permits to run test files in batch with ctest. The former workaround was
                    437:   $ echo q | imach foo.imach
                    438: 
1.195     brouard   439:   Revision 1.194  2015/08/18 13:32:00  brouard
                    440:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    441: 
1.194     brouard   442:   Revision 1.193  2015/08/04 07:17:42  brouard
                    443:   Summary: 0.98q4
                    444: 
1.193     brouard   445:   Revision 1.192  2015/07/16 16:49:02  brouard
                    446:   Summary: Fixing some outputs
                    447: 
1.192     brouard   448:   Revision 1.191  2015/07/14 10:00:33  brouard
                    449:   Summary: Some fixes
                    450: 
1.191     brouard   451:   Revision 1.190  2015/05/05 08:51:13  brouard
                    452:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    453: 
                    454:   Fix 1+age+.
                    455: 
1.190     brouard   456:   Revision 1.189  2015/04/30 14:45:16  brouard
                    457:   Summary: 0.98q2
                    458: 
1.189     brouard   459:   Revision 1.188  2015/04/30 08:27:53  brouard
                    460:   *** empty log message ***
                    461: 
1.188     brouard   462:   Revision 1.187  2015/04/29 09:11:15  brouard
                    463:   *** empty log message ***
                    464: 
1.187     brouard   465:   Revision 1.186  2015/04/23 12:01:52  brouard
                    466:   Summary: V1*age is working now, version 0.98q1
                    467: 
                    468:   Some codes had been disabled in order to simplify and Vn*age was
                    469:   working in the optimization phase, ie, giving correct MLE parameters,
                    470:   but, as usual, outputs were not correct and program core dumped.
                    471: 
1.186     brouard   472:   Revision 1.185  2015/03/11 13:26:42  brouard
                    473:   Summary: Inclusion of compile and links command line for Intel Compiler
                    474: 
1.185     brouard   475:   Revision 1.184  2015/03/11 11:52:39  brouard
                    476:   Summary: Back from Windows 8. Intel Compiler
                    477: 
1.184     brouard   478:   Revision 1.183  2015/03/10 20:34:32  brouard
                    479:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    480: 
                    481:   We use directest instead of original Powell test; probably no
                    482:   incidence on the results, but better justifications;
                    483:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    484:   wrong results.
                    485: 
1.183     brouard   486:   Revision 1.182  2015/02/12 08:19:57  brouard
                    487:   Summary: Trying to keep directest which seems simpler and more general
                    488:   Author: Nicolas Brouard
                    489: 
1.182     brouard   490:   Revision 1.181  2015/02/11 23:22:24  brouard
                    491:   Summary: Comments on Powell added
                    492: 
                    493:   Author:
                    494: 
1.181     brouard   495:   Revision 1.180  2015/02/11 17:33:45  brouard
                    496:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    497: 
1.180     brouard   498:   Revision 1.179  2015/01/04 09:57:06  brouard
                    499:   Summary: back to OS/X
                    500: 
1.179     brouard   501:   Revision 1.178  2015/01/04 09:35:48  brouard
                    502:   *** empty log message ***
                    503: 
1.178     brouard   504:   Revision 1.177  2015/01/03 18:40:56  brouard
                    505:   Summary: Still testing ilc32 on OSX
                    506: 
1.177     brouard   507:   Revision 1.176  2015/01/03 16:45:04  brouard
                    508:   *** empty log message ***
                    509: 
1.176     brouard   510:   Revision 1.175  2015/01/03 16:33:42  brouard
                    511:   *** empty log message ***
                    512: 
1.175     brouard   513:   Revision 1.174  2015/01/03 16:15:49  brouard
                    514:   Summary: Still in cross-compilation
                    515: 
1.174     brouard   516:   Revision 1.173  2015/01/03 12:06:26  brouard
                    517:   Summary: trying to detect cross-compilation
                    518: 
1.173     brouard   519:   Revision 1.172  2014/12/27 12:07:47  brouard
                    520:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    521: 
1.172     brouard   522:   Revision 1.171  2014/12/23 13:26:59  brouard
                    523:   Summary: Back from Visual C
                    524: 
                    525:   Still problem with utsname.h on Windows
                    526: 
1.171     brouard   527:   Revision 1.170  2014/12/23 11:17:12  brouard
                    528:   Summary: Cleaning some \%% back to %%
                    529: 
                    530:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    531: 
1.170     brouard   532:   Revision 1.169  2014/12/22 23:08:31  brouard
                    533:   Summary: 0.98p
                    534: 
                    535:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    536: 
1.169     brouard   537:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   538:   Summary: update
1.169     brouard   539: 
1.168     brouard   540:   Revision 1.167  2014/12/22 13:50:56  brouard
                    541:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    542: 
                    543:   Testing on Linux 64
                    544: 
1.167     brouard   545:   Revision 1.166  2014/12/22 11:40:47  brouard
                    546:   *** empty log message ***
                    547: 
1.166     brouard   548:   Revision 1.165  2014/12/16 11:20:36  brouard
                    549:   Summary: After compiling on Visual C
                    550: 
                    551:   * imach.c (Module): Merging 1.61 to 1.162
                    552: 
1.165     brouard   553:   Revision 1.164  2014/12/16 10:52:11  brouard
                    554:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    555: 
                    556:   * imach.c (Module): Merging 1.61 to 1.162
                    557: 
1.164     brouard   558:   Revision 1.163  2014/12/16 10:30:11  brouard
                    559:   * imach.c (Module): Merging 1.61 to 1.162
                    560: 
1.163     brouard   561:   Revision 1.162  2014/09/25 11:43:39  brouard
                    562:   Summary: temporary backup 0.99!
                    563: 
1.162     brouard   564:   Revision 1.1  2014/09/16 11:06:58  brouard
                    565:   Summary: With some code (wrong) for nlopt
                    566: 
                    567:   Author:
                    568: 
                    569:   Revision 1.161  2014/09/15 20:41:41  brouard
                    570:   Summary: Problem with macro SQR on Intel compiler
                    571: 
1.161     brouard   572:   Revision 1.160  2014/09/02 09:24:05  brouard
                    573:   *** empty log message ***
                    574: 
1.160     brouard   575:   Revision 1.159  2014/09/01 10:34:10  brouard
                    576:   Summary: WIN32
                    577:   Author: Brouard
                    578: 
1.159     brouard   579:   Revision 1.158  2014/08/27 17:11:51  brouard
                    580:   *** empty log message ***
                    581: 
1.158     brouard   582:   Revision 1.157  2014/08/27 16:26:55  brouard
                    583:   Summary: Preparing windows Visual studio version
                    584:   Author: Brouard
                    585: 
                    586:   In order to compile on Visual studio, time.h is now correct and time_t
                    587:   and tm struct should be used. difftime should be used but sometimes I
                    588:   just make the differences in raw time format (time(&now).
                    589:   Trying to suppress #ifdef LINUX
                    590:   Add xdg-open for __linux in order to open default browser.
                    591: 
1.157     brouard   592:   Revision 1.156  2014/08/25 20:10:10  brouard
                    593:   *** empty log message ***
                    594: 
1.156     brouard   595:   Revision 1.155  2014/08/25 18:32:34  brouard
                    596:   Summary: New compile, minor changes
                    597:   Author: Brouard
                    598: 
1.155     brouard   599:   Revision 1.154  2014/06/20 17:32:08  brouard
                    600:   Summary: Outputs now all graphs of convergence to period prevalence
                    601: 
1.154     brouard   602:   Revision 1.153  2014/06/20 16:45:46  brouard
                    603:   Summary: If 3 live state, convergence to period prevalence on same graph
                    604:   Author: Brouard
                    605: 
1.153     brouard   606:   Revision 1.152  2014/06/18 17:54:09  brouard
                    607:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    608: 
1.152     brouard   609:   Revision 1.151  2014/06/18 16:43:30  brouard
                    610:   *** empty log message ***
                    611: 
1.151     brouard   612:   Revision 1.150  2014/06/18 16:42:35  brouard
                    613:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    614:   Author: brouard
                    615: 
1.150     brouard   616:   Revision 1.149  2014/06/18 15:51:14  brouard
                    617:   Summary: Some fixes in parameter files errors
                    618:   Author: Nicolas Brouard
                    619: 
1.149     brouard   620:   Revision 1.148  2014/06/17 17:38:48  brouard
                    621:   Summary: Nothing new
                    622:   Author: Brouard
                    623: 
                    624:   Just a new packaging for OS/X version 0.98nS
                    625: 
1.148     brouard   626:   Revision 1.147  2014/06/16 10:33:11  brouard
                    627:   *** empty log message ***
                    628: 
1.147     brouard   629:   Revision 1.146  2014/06/16 10:20:28  brouard
                    630:   Summary: Merge
                    631:   Author: Brouard
                    632: 
                    633:   Merge, before building revised version.
                    634: 
1.146     brouard   635:   Revision 1.145  2014/06/10 21:23:15  brouard
                    636:   Summary: Debugging with valgrind
                    637:   Author: Nicolas Brouard
                    638: 
                    639:   Lot of changes in order to output the results with some covariates
                    640:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    641:   improve the code.
                    642:   No more memory valgrind error but a lot has to be done in order to
                    643:   continue the work of splitting the code into subroutines.
                    644:   Also, decodemodel has been improved. Tricode is still not
                    645:   optimal. nbcode should be improved. Documentation has been added in
                    646:   the source code.
                    647: 
1.144     brouard   648:   Revision 1.143  2014/01/26 09:45:38  brouard
                    649:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    650: 
                    651:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    652:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    653: 
1.143     brouard   654:   Revision 1.142  2014/01/26 03:57:36  brouard
                    655:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    656: 
                    657:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    658: 
1.142     brouard   659:   Revision 1.141  2014/01/26 02:42:01  brouard
                    660:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    661: 
1.141     brouard   662:   Revision 1.140  2011/09/02 10:37:54  brouard
                    663:   Summary: times.h is ok with mingw32 now.
                    664: 
1.140     brouard   665:   Revision 1.139  2010/06/14 07:50:17  brouard
                    666:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    667:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    668: 
1.139     brouard   669:   Revision 1.138  2010/04/30 18:19:40  brouard
                    670:   *** empty log message ***
                    671: 
1.138     brouard   672:   Revision 1.137  2010/04/29 18:11:38  brouard
                    673:   (Module): Checking covariates for more complex models
                    674:   than V1+V2. A lot of change to be done. Unstable.
                    675: 
1.137     brouard   676:   Revision 1.136  2010/04/26 20:30:53  brouard
                    677:   (Module): merging some libgsl code. Fixing computation
                    678:   of likelione (using inter/intrapolation if mle = 0) in order to
                    679:   get same likelihood as if mle=1.
                    680:   Some cleaning of code and comments added.
                    681: 
1.136     brouard   682:   Revision 1.135  2009/10/29 15:33:14  brouard
                    683:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    684: 
1.135     brouard   685:   Revision 1.134  2009/10/29 13:18:53  brouard
                    686:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    687: 
1.134     brouard   688:   Revision 1.133  2009/07/06 10:21:25  brouard
                    689:   just nforces
                    690: 
1.133     brouard   691:   Revision 1.132  2009/07/06 08:22:05  brouard
                    692:   Many tings
                    693: 
1.132     brouard   694:   Revision 1.131  2009/06/20 16:22:47  brouard
                    695:   Some dimensions resccaled
                    696: 
1.131     brouard   697:   Revision 1.130  2009/05/26 06:44:34  brouard
                    698:   (Module): Max Covariate is now set to 20 instead of 8. A
                    699:   lot of cleaning with variables initialized to 0. Trying to make
                    700:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    701: 
1.130     brouard   702:   Revision 1.129  2007/08/31 13:49:27  lievre
                    703:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    704: 
1.129     lievre    705:   Revision 1.128  2006/06/30 13:02:05  brouard
                    706:   (Module): Clarifications on computing e.j
                    707: 
1.128     brouard   708:   Revision 1.127  2006/04/28 18:11:50  brouard
                    709:   (Module): Yes the sum of survivors was wrong since
                    710:   imach-114 because nhstepm was no more computed in the age
                    711:   loop. Now we define nhstepma in the age loop.
                    712:   (Module): In order to speed up (in case of numerous covariates) we
                    713:   compute health expectancies (without variances) in a first step
                    714:   and then all the health expectancies with variances or standard
                    715:   deviation (needs data from the Hessian matrices) which slows the
                    716:   computation.
                    717:   In the future we should be able to stop the program is only health
                    718:   expectancies and graph are needed without standard deviations.
                    719: 
1.127     brouard   720:   Revision 1.126  2006/04/28 17:23:28  brouard
                    721:   (Module): Yes the sum of survivors was wrong since
                    722:   imach-114 because nhstepm was no more computed in the age
                    723:   loop. Now we define nhstepma in the age loop.
                    724:   Version 0.98h
                    725: 
1.126     brouard   726:   Revision 1.125  2006/04/04 15:20:31  lievre
                    727:   Errors in calculation of health expectancies. Age was not initialized.
                    728:   Forecasting file added.
                    729: 
                    730:   Revision 1.124  2006/03/22 17:13:53  lievre
                    731:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    732:   The log-likelihood is printed in the log file
                    733: 
                    734:   Revision 1.123  2006/03/20 10:52:43  brouard
                    735:   * imach.c (Module): <title> changed, corresponds to .htm file
                    736:   name. <head> headers where missing.
                    737: 
                    738:   * imach.c (Module): Weights can have a decimal point as for
                    739:   English (a comma might work with a correct LC_NUMERIC environment,
                    740:   otherwise the weight is truncated).
                    741:   Modification of warning when the covariates values are not 0 or
                    742:   1.
                    743:   Version 0.98g
                    744: 
                    745:   Revision 1.122  2006/03/20 09:45:41  brouard
                    746:   (Module): Weights can have a decimal point as for
                    747:   English (a comma might work with a correct LC_NUMERIC environment,
                    748:   otherwise the weight is truncated).
                    749:   Modification of warning when the covariates values are not 0 or
                    750:   1.
                    751:   Version 0.98g
                    752: 
                    753:   Revision 1.121  2006/03/16 17:45:01  lievre
                    754:   * imach.c (Module): Comments concerning covariates added
                    755: 
                    756:   * imach.c (Module): refinements in the computation of lli if
                    757:   status=-2 in order to have more reliable computation if stepm is
                    758:   not 1 month. Version 0.98f
                    759: 
                    760:   Revision 1.120  2006/03/16 15:10:38  lievre
                    761:   (Module): refinements in the computation of lli if
                    762:   status=-2 in order to have more reliable computation if stepm is
                    763:   not 1 month. Version 0.98f
                    764: 
                    765:   Revision 1.119  2006/03/15 17:42:26  brouard
                    766:   (Module): Bug if status = -2, the loglikelihood was
                    767:   computed as likelihood omitting the logarithm. Version O.98e
                    768: 
                    769:   Revision 1.118  2006/03/14 18:20:07  brouard
                    770:   (Module): varevsij Comments added explaining the second
                    771:   table of variances if popbased=1 .
                    772:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    773:   (Module): Function pstamp added
                    774:   (Module): Version 0.98d
                    775: 
                    776:   Revision 1.117  2006/03/14 17:16:22  brouard
                    777:   (Module): varevsij Comments added explaining the second
                    778:   table of variances if popbased=1 .
                    779:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    780:   (Module): Function pstamp added
                    781:   (Module): Version 0.98d
                    782: 
                    783:   Revision 1.116  2006/03/06 10:29:27  brouard
                    784:   (Module): Variance-covariance wrong links and
                    785:   varian-covariance of ej. is needed (Saito).
                    786: 
                    787:   Revision 1.115  2006/02/27 12:17:45  brouard
                    788:   (Module): One freematrix added in mlikeli! 0.98c
                    789: 
                    790:   Revision 1.114  2006/02/26 12:57:58  brouard
                    791:   (Module): Some improvements in processing parameter
                    792:   filename with strsep.
                    793: 
                    794:   Revision 1.113  2006/02/24 14:20:24  brouard
                    795:   (Module): Memory leaks checks with valgrind and:
                    796:   datafile was not closed, some imatrix were not freed and on matrix
                    797:   allocation too.
                    798: 
                    799:   Revision 1.112  2006/01/30 09:55:26  brouard
                    800:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    801: 
                    802:   Revision 1.111  2006/01/25 20:38:18  brouard
                    803:   (Module): Lots of cleaning and bugs added (Gompertz)
                    804:   (Module): Comments can be added in data file. Missing date values
                    805:   can be a simple dot '.'.
                    806: 
                    807:   Revision 1.110  2006/01/25 00:51:50  brouard
                    808:   (Module): Lots of cleaning and bugs added (Gompertz)
                    809: 
                    810:   Revision 1.109  2006/01/24 19:37:15  brouard
                    811:   (Module): Comments (lines starting with a #) are allowed in data.
                    812: 
                    813:   Revision 1.108  2006/01/19 18:05:42  lievre
                    814:   Gnuplot problem appeared...
                    815:   To be fixed
                    816: 
                    817:   Revision 1.107  2006/01/19 16:20:37  brouard
                    818:   Test existence of gnuplot in imach path
                    819: 
                    820:   Revision 1.106  2006/01/19 13:24:36  brouard
                    821:   Some cleaning and links added in html output
                    822: 
                    823:   Revision 1.105  2006/01/05 20:23:19  lievre
                    824:   *** empty log message ***
                    825: 
                    826:   Revision 1.104  2005/09/30 16:11:43  lievre
                    827:   (Module): sump fixed, loop imx fixed, and simplifications.
                    828:   (Module): If the status is missing at the last wave but we know
                    829:   that the person is alive, then we can code his/her status as -2
                    830:   (instead of missing=-1 in earlier versions) and his/her
                    831:   contributions to the likelihood is 1 - Prob of dying from last
                    832:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    833:   the healthy state at last known wave). Version is 0.98
                    834: 
                    835:   Revision 1.103  2005/09/30 15:54:49  lievre
                    836:   (Module): sump fixed, loop imx fixed, and simplifications.
                    837: 
                    838:   Revision 1.102  2004/09/15 17:31:30  brouard
                    839:   Add the possibility to read data file including tab characters.
                    840: 
                    841:   Revision 1.101  2004/09/15 10:38:38  brouard
                    842:   Fix on curr_time
                    843: 
                    844:   Revision 1.100  2004/07/12 18:29:06  brouard
                    845:   Add version for Mac OS X. Just define UNIX in Makefile
                    846: 
                    847:   Revision 1.99  2004/06/05 08:57:40  brouard
                    848:   *** empty log message ***
                    849: 
                    850:   Revision 1.98  2004/05/16 15:05:56  brouard
                    851:   New version 0.97 . First attempt to estimate force of mortality
                    852:   directly from the data i.e. without the need of knowing the health
                    853:   state at each age, but using a Gompertz model: log u =a + b*age .
                    854:   This is the basic analysis of mortality and should be done before any
                    855:   other analysis, in order to test if the mortality estimated from the
                    856:   cross-longitudinal survey is different from the mortality estimated
                    857:   from other sources like vital statistic data.
                    858: 
                    859:   The same imach parameter file can be used but the option for mle should be -3.
                    860: 
1.133     brouard   861:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   862:   former routines in order to include the new code within the former code.
                    863: 
                    864:   The output is very simple: only an estimate of the intercept and of
                    865:   the slope with 95% confident intervals.
                    866: 
                    867:   Current limitations:
                    868:   A) Even if you enter covariates, i.e. with the
                    869:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    870:   B) There is no computation of Life Expectancy nor Life Table.
                    871: 
                    872:   Revision 1.97  2004/02/20 13:25:42  lievre
                    873:   Version 0.96d. Population forecasting command line is (temporarily)
                    874:   suppressed.
                    875: 
                    876:   Revision 1.96  2003/07/15 15:38:55  brouard
                    877:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    878:   rewritten within the same printf. Workaround: many printfs.
                    879: 
                    880:   Revision 1.95  2003/07/08 07:54:34  brouard
                    881:   * imach.c (Repository):
                    882:   (Repository): Using imachwizard code to output a more meaningful covariance
                    883:   matrix (cov(a12,c31) instead of numbers.
                    884: 
                    885:   Revision 1.94  2003/06/27 13:00:02  brouard
                    886:   Just cleaning
                    887: 
                    888:   Revision 1.93  2003/06/25 16:33:55  brouard
                    889:   (Module): On windows (cygwin) function asctime_r doesn't
                    890:   exist so I changed back to asctime which exists.
                    891:   (Module): Version 0.96b
                    892: 
                    893:   Revision 1.92  2003/06/25 16:30:45  brouard
                    894:   (Module): On windows (cygwin) function asctime_r doesn't
                    895:   exist so I changed back to asctime which exists.
                    896: 
                    897:   Revision 1.91  2003/06/25 15:30:29  brouard
                    898:   * imach.c (Repository): Duplicated warning errors corrected.
                    899:   (Repository): Elapsed time after each iteration is now output. It
                    900:   helps to forecast when convergence will be reached. Elapsed time
                    901:   is stamped in powell.  We created a new html file for the graphs
                    902:   concerning matrix of covariance. It has extension -cov.htm.
                    903: 
                    904:   Revision 1.90  2003/06/24 12:34:15  brouard
                    905:   (Module): Some bugs corrected for windows. Also, when
                    906:   mle=-1 a template is output in file "or"mypar.txt with the design
                    907:   of the covariance matrix to be input.
                    908: 
                    909:   Revision 1.89  2003/06/24 12:30:52  brouard
                    910:   (Module): Some bugs corrected for windows. Also, when
                    911:   mle=-1 a template is output in file "or"mypar.txt with the design
                    912:   of the covariance matrix to be input.
                    913: 
                    914:   Revision 1.88  2003/06/23 17:54:56  brouard
                    915:   * 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.
                    916: 
                    917:   Revision 1.87  2003/06/18 12:26:01  brouard
                    918:   Version 0.96
                    919: 
                    920:   Revision 1.86  2003/06/17 20:04:08  brouard
                    921:   (Module): Change position of html and gnuplot routines and added
                    922:   routine fileappend.
                    923: 
                    924:   Revision 1.85  2003/06/17 13:12:43  brouard
                    925:   * imach.c (Repository): Check when date of death was earlier that
                    926:   current date of interview. It may happen when the death was just
                    927:   prior to the death. In this case, dh was negative and likelihood
                    928:   was wrong (infinity). We still send an "Error" but patch by
                    929:   assuming that the date of death was just one stepm after the
                    930:   interview.
                    931:   (Repository): Because some people have very long ID (first column)
                    932:   we changed int to long in num[] and we added a new lvector for
                    933:   memory allocation. But we also truncated to 8 characters (left
                    934:   truncation)
                    935:   (Repository): No more line truncation errors.
                    936: 
                    937:   Revision 1.84  2003/06/13 21:44:43  brouard
                    938:   * imach.c (Repository): Replace "freqsummary" at a correct
                    939:   place. It differs from routine "prevalence" which may be called
                    940:   many times. Probs is memory consuming and must be used with
                    941:   parcimony.
                    942:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    943: 
                    944:   Revision 1.83  2003/06/10 13:39:11  lievre
                    945:   *** empty log message ***
                    946: 
                    947:   Revision 1.82  2003/06/05 15:57:20  brouard
                    948:   Add log in  imach.c and  fullversion number is now printed.
                    949: 
                    950: */
                    951: /*
                    952:    Interpolated Markov Chain
                    953: 
                    954:   Short summary of the programme:
                    955:   
1.227     brouard   956:   This program computes Healthy Life Expectancies or State-specific
                    957:   (if states aren't health statuses) Expectancies from
                    958:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    959: 
                    960:   -1- a first survey ("cross") where individuals from different ages
                    961:   are interviewed on their health status or degree of disability (in
                    962:   the case of a health survey which is our main interest)
                    963: 
                    964:   -2- at least a second wave of interviews ("longitudinal") which
                    965:   measure each change (if any) in individual health status.  Health
                    966:   expectancies are computed from the time spent in each health state
                    967:   according to a model. More health states you consider, more time is
                    968:   necessary to reach the Maximum Likelihood of the parameters involved
                    969:   in the model.  The simplest model is the multinomial logistic model
                    970:   where pij is the probability to be observed in state j at the second
                    971:   wave conditional to be observed in state i at the first
                    972:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    973:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    974:   have a more complex model than "constant and age", you should modify
                    975:   the program where the markup *Covariates have to be included here
                    976:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   977:   convergence.
                    978: 
                    979:   The advantage of this computer programme, compared to a simple
                    980:   multinomial logistic model, is clear when the delay between waves is not
                    981:   identical for each individual. Also, if a individual missed an
                    982:   intermediate interview, the information is lost, but taken into
                    983:   account using an interpolation or extrapolation.  
                    984: 
                    985:   hPijx is the probability to be observed in state i at age x+h
                    986:   conditional to the observed state i at age x. The delay 'h' can be
                    987:   split into an exact number (nh*stepm) of unobserved intermediate
                    988:   states. This elementary transition (by month, quarter,
                    989:   semester or year) is modelled as a multinomial logistic.  The hPx
                    990:   matrix is simply the matrix product of nh*stepm elementary matrices
                    991:   and the contribution of each individual to the likelihood is simply
                    992:   hPijx.
                    993: 
                    994:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   995:   of the life expectancies. It also computes the period (stable) prevalence.
                    996: 
                    997: Back prevalence and projections:
1.227     brouard   998: 
                    999:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1000:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1001:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1002:    mobilavproj)
                   1003: 
                   1004:     Computes the back prevalence limit for any combination of
                   1005:     covariate values k at any age between ageminpar and agemaxpar and
                   1006:     returns it in **bprlim. In the loops,
                   1007: 
                   1008:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1009:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1010: 
                   1011:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1012:    Computes for any combination of covariates k and any age between bage and fage 
                   1013:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1014:                        oldm=oldms;savm=savms;
1.227     brouard  1015: 
1.267     brouard  1016:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1017:      Computes the transition matrix starting at age 'age' over
                   1018:      'nhstepm*hstepm*stepm' months (i.e. until
                   1019:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1020:      nhstepm*hstepm matrices. 
                   1021: 
                   1022:      Returns p3mat[i][j][h] after calling
                   1023:      p3mat[i][j][h]=matprod2(newm,
                   1024:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1025:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1026:      oldm);
1.226     brouard  1027: 
                   1028: Important routines
                   1029: 
                   1030: - func (or funcone), computes logit (pij) distinguishing
                   1031:   o fixed variables (single or product dummies or quantitative);
                   1032:   o varying variables by:
                   1033:    (1) wave (single, product dummies, quantitative), 
                   1034:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1035:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1036:        % varying dummy (not done) or quantitative (not done);
                   1037: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1038:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1039: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                   1040:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                   1041:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1042: 
1.226     brouard  1043: 
                   1044:   
1.133     brouard  1045:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1046:            Institut national d'études démographiques, Paris.
1.126     brouard  1047:   This software have been partly granted by Euro-REVES, a concerted action
                   1048:   from the European Union.
                   1049:   It is copyrighted identically to a GNU software product, ie programme and
                   1050:   software can be distributed freely for non commercial use. Latest version
                   1051:   can be accessed at http://euroreves.ined.fr/imach .
                   1052: 
                   1053:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1054:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1055:   
                   1056:   **********************************************************************/
                   1057: /*
                   1058:   main
                   1059:   read parameterfile
                   1060:   read datafile
                   1061:   concatwav
                   1062:   freqsummary
                   1063:   if (mle >= 1)
                   1064:     mlikeli
                   1065:   print results files
                   1066:   if mle==1 
                   1067:      computes hessian
                   1068:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1069:       begin-prev-date,...
                   1070:   open gnuplot file
                   1071:   open html file
1.145     brouard  1072:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1073:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1074:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1075:     freexexit2 possible for memory heap.
                   1076: 
                   1077:   h Pij x                         | pij_nom  ficrestpij
                   1078:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1079:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1080:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1081: 
                   1082:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1083:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1084:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1085:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1086:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1087: 
1.126     brouard  1088:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1089:   health expectancies
                   1090:   Variance-covariance of DFLE
                   1091:   prevalence()
                   1092:    movingaverage()
                   1093:   varevsij() 
                   1094:   if popbased==1 varevsij(,popbased)
                   1095:   total life expectancies
                   1096:   Variance of period (stable) prevalence
                   1097:  end
                   1098: */
                   1099: 
1.187     brouard  1100: /* #define DEBUG */
                   1101: /* #define DEBUGBRENT */
1.203     brouard  1102: /* #define DEBUGLINMIN */
                   1103: /* #define DEBUGHESS */
                   1104: #define DEBUGHESSIJ
1.224     brouard  1105: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1106: #define POWELL /* Instead of NLOPT */
1.224     brouard  1107: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1108: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1109: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1110: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1111: 
                   1112: #include <math.h>
                   1113: #include <stdio.h>
                   1114: #include <stdlib.h>
                   1115: #include <string.h>
1.226     brouard  1116: #include <ctype.h>
1.159     brouard  1117: 
                   1118: #ifdef _WIN32
                   1119: #include <io.h>
1.172     brouard  1120: #include <windows.h>
                   1121: #include <tchar.h>
1.159     brouard  1122: #else
1.126     brouard  1123: #include <unistd.h>
1.159     brouard  1124: #endif
1.126     brouard  1125: 
                   1126: #include <limits.h>
                   1127: #include <sys/types.h>
1.171     brouard  1128: 
                   1129: #if defined(__GNUC__)
                   1130: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1131: #endif
                   1132: 
1.126     brouard  1133: #include <sys/stat.h>
                   1134: #include <errno.h>
1.159     brouard  1135: /* extern int errno; */
1.126     brouard  1136: 
1.157     brouard  1137: /* #ifdef LINUX */
                   1138: /* #include <time.h> */
                   1139: /* #include "timeval.h" */
                   1140: /* #else */
                   1141: /* #include <sys/time.h> */
                   1142: /* #endif */
                   1143: 
1.126     brouard  1144: #include <time.h>
                   1145: 
1.136     brouard  1146: #ifdef GSL
                   1147: #include <gsl/gsl_errno.h>
                   1148: #include <gsl/gsl_multimin.h>
                   1149: #endif
                   1150: 
1.167     brouard  1151: 
1.162     brouard  1152: #ifdef NLOPT
                   1153: #include <nlopt.h>
                   1154: typedef struct {
                   1155:   double (* function)(double [] );
                   1156: } myfunc_data ;
                   1157: #endif
                   1158: 
1.126     brouard  1159: /* #include <libintl.h> */
                   1160: /* #define _(String) gettext (String) */
                   1161: 
1.251     brouard  1162: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1163: 
                   1164: #define GNUPLOTPROGRAM "gnuplot"
                   1165: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1166: #define FILENAMELENGTH 132
                   1167: 
                   1168: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1169: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1170: 
1.144     brouard  1171: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1172: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1173: 
                   1174: #define NINTERVMAX 8
1.144     brouard  1175: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1176: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.318     brouard  1177: #define NCOVMAX 30  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1178: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1179: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1180: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1181: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1182: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1183: /* #define AGESUP 130 */
1.288     brouard  1184: /* #define AGESUP 150 */
                   1185: #define AGESUP 200
1.268     brouard  1186: #define AGEINF 0
1.218     brouard  1187: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1188: #define AGEBASE 40
1.194     brouard  1189: #define AGEOVERFLOW 1.e20
1.164     brouard  1190: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1191: #ifdef _WIN32
                   1192: #define DIRSEPARATOR '\\'
                   1193: #define CHARSEPARATOR "\\"
                   1194: #define ODIRSEPARATOR '/'
                   1195: #else
1.126     brouard  1196: #define DIRSEPARATOR '/'
                   1197: #define CHARSEPARATOR "/"
                   1198: #define ODIRSEPARATOR '\\'
                   1199: #endif
                   1200: 
1.321   ! brouard  1201: /* $Id: imach.c,v 1.320 2022/06/02 05:10:11 brouard Exp $ */
1.126     brouard  1202: /* $State: Exp $ */
1.196     brouard  1203: #include "version.h"
                   1204: char version[]=__IMACH_VERSION__;
1.316     brouard  1205: char copyright[]="May 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.321   ! brouard  1206: char fullversion[]="$Revision: 1.320 $ $Date: 2022/06/02 05:10:11 $"; 
1.126     brouard  1207: char strstart[80];
                   1208: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1209: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1210: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1211: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1212: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1213: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1214: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1215: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1216: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1217: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1218: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1219: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1220: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1221: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1222: int nsd=0; /**< Total number of single dummy variables (output) */
                   1223: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1224: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1225: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1226: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1227: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1228: int cptcov=0; /* Working variable */
1.290     brouard  1229: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1230: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1231: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1232: int nlstate=2; /* Number of live states */
                   1233: int ndeath=1; /* Number of dead states */
1.130     brouard  1234: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1235: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1236: int popbased=0;
                   1237: 
                   1238: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1239: int maxwav=0; /* Maxim number of waves */
                   1240: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1241: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1242: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1243:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1244: int mle=1, weightopt=0;
1.126     brouard  1245: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1246: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1247: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1248:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1249: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1250: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1251: 
1.130     brouard  1252: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1253: double **matprod2(); /* test */
1.126     brouard  1254: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1255: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1256: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1257: 
1.136     brouard  1258: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1259: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1260: FILE *ficlog, *ficrespow;
1.130     brouard  1261: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1262: double fretone; /* Only one call to likelihood */
1.130     brouard  1263: long ipmx=0; /* Number of contributions */
1.126     brouard  1264: double sw; /* Sum of weights */
                   1265: char filerespow[FILENAMELENGTH];
                   1266: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1267: FILE *ficresilk;
                   1268: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1269: FILE *ficresprobmorprev;
                   1270: FILE *fichtm, *fichtmcov; /* Html File */
                   1271: FILE *ficreseij;
                   1272: char filerese[FILENAMELENGTH];
                   1273: FILE *ficresstdeij;
                   1274: char fileresstde[FILENAMELENGTH];
                   1275: FILE *ficrescveij;
                   1276: char filerescve[FILENAMELENGTH];
                   1277: FILE  *ficresvij;
                   1278: char fileresv[FILENAMELENGTH];
1.269     brouard  1279: 
1.126     brouard  1280: char title[MAXLINE];
1.234     brouard  1281: char model[MAXLINE]; /**< The model line */
1.217     brouard  1282: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1283: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1284: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1285: char command[FILENAMELENGTH];
                   1286: int  outcmd=0;
                   1287: 
1.217     brouard  1288: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1289: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1290: char filelog[FILENAMELENGTH]; /* Log file */
                   1291: char filerest[FILENAMELENGTH];
                   1292: char fileregp[FILENAMELENGTH];
                   1293: char popfile[FILENAMELENGTH];
                   1294: 
                   1295: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1296: 
1.157     brouard  1297: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1298: /* struct timezone tzp; */
                   1299: /* extern int gettimeofday(); */
                   1300: struct tm tml, *gmtime(), *localtime();
                   1301: 
                   1302: extern time_t time();
                   1303: 
                   1304: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1305: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1306: struct tm tm;
                   1307: 
1.126     brouard  1308: char strcurr[80], strfor[80];
                   1309: 
                   1310: char *endptr;
                   1311: long lval;
                   1312: double dval;
                   1313: 
                   1314: #define NR_END 1
                   1315: #define FREE_ARG char*
                   1316: #define FTOL 1.0e-10
                   1317: 
                   1318: #define NRANSI 
1.240     brouard  1319: #define ITMAX 200
                   1320: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1321: 
                   1322: #define TOL 2.0e-4 
                   1323: 
                   1324: #define CGOLD 0.3819660 
                   1325: #define ZEPS 1.0e-10 
                   1326: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1327: 
                   1328: #define GOLD 1.618034 
                   1329: #define GLIMIT 100.0 
                   1330: #define TINY 1.0e-20 
                   1331: 
                   1332: static double maxarg1,maxarg2;
                   1333: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1334: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1335:   
                   1336: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1337: #define rint(a) floor(a+0.5)
1.166     brouard  1338: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1339: #define mytinydouble 1.0e-16
1.166     brouard  1340: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1341: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1342: /* static double dsqrarg; */
                   1343: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1344: static double sqrarg;
                   1345: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1346: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1347: int agegomp= AGEGOMP;
                   1348: 
                   1349: int imx; 
                   1350: int stepm=1;
                   1351: /* Stepm, step in month: minimum step interpolation*/
                   1352: 
                   1353: int estepm;
                   1354: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1355: 
                   1356: int m,nb;
                   1357: long *num;
1.197     brouard  1358: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1359: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1360:                   covariate for which somebody answered excluding 
                   1361:                   undefined. Usually 2: 0 and 1. */
                   1362: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1363:                             covariate for which somebody answered including 
                   1364:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1365: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1366: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1367: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1368: double *ageexmed,*agecens;
                   1369: double dateintmean=0;
1.296     brouard  1370:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1371:   double anprojf, mprojf, jprojf;
1.126     brouard  1372: 
1.296     brouard  1373:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1374:   double anbackf, mbackf, jbackf;
                   1375:   double jintmean,mintmean,aintmean;  
1.126     brouard  1376: double *weight;
                   1377: int **s; /* Status */
1.141     brouard  1378: double *agedc;
1.145     brouard  1379: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1380:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1381:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1382: double **coqvar; /* Fixed quantitative covariate nqv */
                   1383: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1384: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1385: double  idx; 
                   1386: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1387: /* Some documentation */
                   1388:       /*   Design original data
                   1389:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1390:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1391:        *                                                             ntv=3     nqtv=1
                   1392:        *  cptcovn number of covariates (not including constant and age) = # of + plus 1 = 10+1=11
                   1393:        * For time varying covariate, quanti or dummies
                   1394:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1395:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1396:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1397:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
                   1398:        *       covar[k,i], value of kth fixed covariate dummy or quanti :
                   1399:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1400:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1401:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1402:        */
                   1403: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1404: /* 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
                   1405:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1406:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1407: */
1.319     brouard  1408: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1409: /*    k        1  2   3   4     5    6    7     8    9 */
                   1410: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1411:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1412:                                                          /* product */
                   1413: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1414:                                                          /*(single or product without age), 2 dummy*/
                   1415:                                                          /* with age product, 3 quant with age product*/
                   1416: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1417: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   1418: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1419: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1420: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1421: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1422: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1423: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1424: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1425: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1426: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
                   1427: /* 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  1428: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1429: /* Type                    */
                   1430: /* V         1  2  3  4  5 */
                   1431: /*           F  F  V  V  V */
                   1432: /*           D  Q  D  D  Q */
                   1433: /*                         */
                   1434: int *TvarsD;
                   1435: int *TvarsDind;
                   1436: int *TvarsQ;
                   1437: int *TvarsQind;
                   1438: 
1.318     brouard  1439: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1440: int nresult=0;
1.258     brouard  1441: int parameterline=0; /* # of the parameter (type) line */
1.318     brouard  1442: int TKresult[MAXRESULTLINESPONE];
                   1443: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1444: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1445: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1446: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1447: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1448: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1449: 
                   1450: /* 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
                   1451:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1452:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1453: */
1.234     brouard  1454: /* 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  1455: 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 */
                   1456: 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 */
                   1457: 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 */
                   1458: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1459: 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 */
                   1460: 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  1461: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1462: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1463: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1464: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1465: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1466: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1467: 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 */
                   1468: 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 */
                   1469: 
1.230     brouard  1470: int *Tvarsel; /**< Selected covariates for output */
                   1471: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1472: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1473: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1474: 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  1475: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1476: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1477: int *Tage;
1.227     brouard  1478: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1479: 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  1480: 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*/ 
                   1481: 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  1482: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1483: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1484: int **Tvard;
                   1485: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1486: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1487: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1488:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1489:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1490: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1491: double *lsurv, *lpop, *tpop;
                   1492: 
1.231     brouard  1493: #define FD 1; /* Fixed dummy covariate */
                   1494: #define FQ 2; /* Fixed quantitative covariate */
                   1495: #define FP 3; /* Fixed product covariate */
                   1496: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1497: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1498: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1499: #define VD 10; /* Varying dummy covariate */
                   1500: #define VQ 11; /* Varying quantitative covariate */
                   1501: #define VP 12; /* Varying product covariate */
                   1502: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1503: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1504: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1505: #define APFD 16; /* Age product * fixed dummy covariate */
                   1506: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1507: #define APVD 18; /* Age product * varying dummy covariate */
                   1508: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1509: 
                   1510: #define FTYPE 1; /* Fixed covariate */
                   1511: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1512: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1513: 
                   1514: struct kmodel{
                   1515:        int maintype; /* main type */
                   1516:        int subtype; /* subtype */
                   1517: };
                   1518: struct kmodel modell[NCOVMAX];
                   1519: 
1.143     brouard  1520: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1521: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1522: 
                   1523: /**************** split *************************/
                   1524: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1525: {
                   1526:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1527:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1528:   */ 
                   1529:   char *ss;                            /* pointer */
1.186     brouard  1530:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1531: 
                   1532:   l1 = strlen(path );                  /* length of path */
                   1533:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1534:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1535:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1536:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1537:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1538:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1539:     /* get current working directory */
                   1540:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1541: #ifdef WIN32
                   1542:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1543: #else
                   1544:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1545: #endif
1.126     brouard  1546:       return( GLOCK_ERROR_GETCWD );
                   1547:     }
                   1548:     /* got dirc from getcwd*/
                   1549:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1550:   } else {                             /* strip directory from path */
1.126     brouard  1551:     ss++;                              /* after this, the filename */
                   1552:     l2 = strlen( ss );                 /* length of filename */
                   1553:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1554:     strcpy( name, ss );                /* save file name */
                   1555:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1556:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1557:     printf(" DIRC2 = %s \n",dirc);
                   1558:   }
                   1559:   /* We add a separator at the end of dirc if not exists */
                   1560:   l1 = strlen( dirc );                 /* length of directory */
                   1561:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1562:     dirc[l1] =  DIRSEPARATOR;
                   1563:     dirc[l1+1] = 0; 
                   1564:     printf(" DIRC3 = %s \n",dirc);
                   1565:   }
                   1566:   ss = strrchr( name, '.' );           /* find last / */
                   1567:   if (ss >0){
                   1568:     ss++;
                   1569:     strcpy(ext,ss);                    /* save extension */
                   1570:     l1= strlen( name);
                   1571:     l2= strlen(ss)+1;
                   1572:     strncpy( finame, name, l1-l2);
                   1573:     finame[l1-l2]= 0;
                   1574:   }
                   1575: 
                   1576:   return( 0 );                         /* we're done */
                   1577: }
                   1578: 
                   1579: 
                   1580: /******************************************/
                   1581: 
                   1582: void replace_back_to_slash(char *s, char*t)
                   1583: {
                   1584:   int i;
                   1585:   int lg=0;
                   1586:   i=0;
                   1587:   lg=strlen(t);
                   1588:   for(i=0; i<= lg; i++) {
                   1589:     (s[i] = t[i]);
                   1590:     if (t[i]== '\\') s[i]='/';
                   1591:   }
                   1592: }
                   1593: 
1.132     brouard  1594: char *trimbb(char *out, char *in)
1.137     brouard  1595: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1596:   char *s;
                   1597:   s=out;
                   1598:   while (*in != '\0'){
1.137     brouard  1599:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1600:       in++;
                   1601:     }
                   1602:     *out++ = *in++;
                   1603:   }
                   1604:   *out='\0';
                   1605:   return s;
                   1606: }
                   1607: 
1.187     brouard  1608: /* char *substrchaine(char *out, char *in, char *chain) */
                   1609: /* { */
                   1610: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1611: /*   char *s, *t; */
                   1612: /*   t=in;s=out; */
                   1613: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1614: /*     *out++ = *in++; */
                   1615: /*   } */
                   1616: 
                   1617: /*   /\* *in matches *chain *\/ */
                   1618: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1619: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1620: /*   } */
                   1621: /*   in--; chain--; */
                   1622: /*   while ( (*in != '\0')){ */
                   1623: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1624: /*     *out++ = *in++; */
                   1625: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1626: /*   } */
                   1627: /*   *out='\0'; */
                   1628: /*   out=s; */
                   1629: /*   return out; */
                   1630: /* } */
                   1631: char *substrchaine(char *out, char *in, char *chain)
                   1632: {
                   1633:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1634:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1635: 
                   1636:   char *strloc;
                   1637: 
                   1638:   strcpy (out, in); 
                   1639:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1640:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1641:   if(strloc != NULL){ 
                   1642:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1643:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1644:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1645:   }
                   1646:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1647:   return out;
                   1648: }
                   1649: 
                   1650: 
1.145     brouard  1651: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1652: {
1.187     brouard  1653:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1654:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1655:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1656:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1657:   */
1.160     brouard  1658:   char *s, *t;
1.145     brouard  1659:   t=in;s=in;
                   1660:   while ((*in != occ) && (*in != '\0')){
                   1661:     *alocc++ = *in++;
                   1662:   }
                   1663:   if( *in == occ){
                   1664:     *(alocc)='\0';
                   1665:     s=++in;
                   1666:   }
                   1667:  
                   1668:   if (s == t) {/* occ not found */
                   1669:     *(alocc-(in-s))='\0';
                   1670:     in=s;
                   1671:   }
                   1672:   while ( *in != '\0'){
                   1673:     *blocc++ = *in++;
                   1674:   }
                   1675: 
                   1676:   *blocc='\0';
                   1677:   return t;
                   1678: }
1.137     brouard  1679: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1680: {
1.187     brouard  1681:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1682:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1683:      gives blocc="abcdef2ghi" and alocc="j".
                   1684:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1685:   */
                   1686:   char *s, *t;
                   1687:   t=in;s=in;
                   1688:   while (*in != '\0'){
                   1689:     while( *in == occ){
                   1690:       *blocc++ = *in++;
                   1691:       s=in;
                   1692:     }
                   1693:     *blocc++ = *in++;
                   1694:   }
                   1695:   if (s == t) /* occ not found */
                   1696:     *(blocc-(in-s))='\0';
                   1697:   else
                   1698:     *(blocc-(in-s)-1)='\0';
                   1699:   in=s;
                   1700:   while ( *in != '\0'){
                   1701:     *alocc++ = *in++;
                   1702:   }
                   1703: 
                   1704:   *alocc='\0';
                   1705:   return s;
                   1706: }
                   1707: 
1.126     brouard  1708: int nbocc(char *s, char occ)
                   1709: {
                   1710:   int i,j=0;
                   1711:   int lg=20;
                   1712:   i=0;
                   1713:   lg=strlen(s);
                   1714:   for(i=0; i<= lg; i++) {
1.234     brouard  1715:     if  (s[i] == occ ) j++;
1.126     brouard  1716:   }
                   1717:   return j;
                   1718: }
                   1719: 
1.137     brouard  1720: /* void cutv(char *u,char *v, char*t, char occ) */
                   1721: /* { */
                   1722: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1723: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1724: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1725: /*   int i,lg,j,p=0; */
                   1726: /*   i=0; */
                   1727: /*   lg=strlen(t); */
                   1728: /*   for(j=0; j<=lg-1; j++) { */
                   1729: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1730: /*   } */
1.126     brouard  1731: 
1.137     brouard  1732: /*   for(j=0; j<p; j++) { */
                   1733: /*     (u[j] = t[j]); */
                   1734: /*   } */
                   1735: /*      u[p]='\0'; */
1.126     brouard  1736: 
1.137     brouard  1737: /*    for(j=0; j<= lg; j++) { */
                   1738: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1739: /*   } */
                   1740: /* } */
1.126     brouard  1741: 
1.160     brouard  1742: #ifdef _WIN32
                   1743: char * strsep(char **pp, const char *delim)
                   1744: {
                   1745:   char *p, *q;
                   1746:          
                   1747:   if ((p = *pp) == NULL)
                   1748:     return 0;
                   1749:   if ((q = strpbrk (p, delim)) != NULL)
                   1750:   {
                   1751:     *pp = q + 1;
                   1752:     *q = '\0';
                   1753:   }
                   1754:   else
                   1755:     *pp = 0;
                   1756:   return p;
                   1757: }
                   1758: #endif
                   1759: 
1.126     brouard  1760: /********************** nrerror ********************/
                   1761: 
                   1762: void nrerror(char error_text[])
                   1763: {
                   1764:   fprintf(stderr,"ERREUR ...\n");
                   1765:   fprintf(stderr,"%s\n",error_text);
                   1766:   exit(EXIT_FAILURE);
                   1767: }
                   1768: /*********************** vector *******************/
                   1769: double *vector(int nl, int nh)
                   1770: {
                   1771:   double *v;
                   1772:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1773:   if (!v) nrerror("allocation failure in vector");
                   1774:   return v-nl+NR_END;
                   1775: }
                   1776: 
                   1777: /************************ free vector ******************/
                   1778: void free_vector(double*v, int nl, int nh)
                   1779: {
                   1780:   free((FREE_ARG)(v+nl-NR_END));
                   1781: }
                   1782: 
                   1783: /************************ivector *******************************/
                   1784: int *ivector(long nl,long nh)
                   1785: {
                   1786:   int *v;
                   1787:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1788:   if (!v) nrerror("allocation failure in ivector");
                   1789:   return v-nl+NR_END;
                   1790: }
                   1791: 
                   1792: /******************free ivector **************************/
                   1793: void free_ivector(int *v, long nl, long nh)
                   1794: {
                   1795:   free((FREE_ARG)(v+nl-NR_END));
                   1796: }
                   1797: 
                   1798: /************************lvector *******************************/
                   1799: long *lvector(long nl,long nh)
                   1800: {
                   1801:   long *v;
                   1802:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1803:   if (!v) nrerror("allocation failure in ivector");
                   1804:   return v-nl+NR_END;
                   1805: }
                   1806: 
                   1807: /******************free lvector **************************/
                   1808: void free_lvector(long *v, long nl, long nh)
                   1809: {
                   1810:   free((FREE_ARG)(v+nl-NR_END));
                   1811: }
                   1812: 
                   1813: /******************* imatrix *******************************/
                   1814: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1815:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1816: { 
                   1817:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1818:   int **m; 
                   1819:   
                   1820:   /* allocate pointers to rows */ 
                   1821:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1822:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1823:   m += NR_END; 
                   1824:   m -= nrl; 
                   1825:   
                   1826:   
                   1827:   /* allocate rows and set pointers to them */ 
                   1828:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1829:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1830:   m[nrl] += NR_END; 
                   1831:   m[nrl] -= ncl; 
                   1832:   
                   1833:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1834:   
                   1835:   /* return pointer to array of pointers to rows */ 
                   1836:   return m; 
                   1837: } 
                   1838: 
                   1839: /****************** free_imatrix *************************/
                   1840: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1841:       int **m;
                   1842:       long nch,ncl,nrh,nrl; 
                   1843:      /* free an int matrix allocated by imatrix() */ 
                   1844: { 
                   1845:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1846:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1847: } 
                   1848: 
                   1849: /******************* matrix *******************************/
                   1850: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1851: {
                   1852:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1853:   double **m;
                   1854: 
                   1855:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1856:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1857:   m += NR_END;
                   1858:   m -= nrl;
                   1859: 
                   1860:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1861:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1862:   m[nrl] += NR_END;
                   1863:   m[nrl] -= ncl;
                   1864: 
                   1865:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1866:   return m;
1.145     brouard  1867:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1868: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1869: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1870:    */
                   1871: }
                   1872: 
                   1873: /*************************free matrix ************************/
                   1874: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1875: {
                   1876:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1877:   free((FREE_ARG)(m+nrl-NR_END));
                   1878: }
                   1879: 
                   1880: /******************* ma3x *******************************/
                   1881: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1882: {
                   1883:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1884:   double ***m;
                   1885: 
                   1886:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1887:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1888:   m += NR_END;
                   1889:   m -= nrl;
                   1890: 
                   1891:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1892:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1893:   m[nrl] += NR_END;
                   1894:   m[nrl] -= ncl;
                   1895: 
                   1896:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1897: 
                   1898:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1899:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1900:   m[nrl][ncl] += NR_END;
                   1901:   m[nrl][ncl] -= nll;
                   1902:   for (j=ncl+1; j<=nch; j++) 
                   1903:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1904:   
                   1905:   for (i=nrl+1; i<=nrh; i++) {
                   1906:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1907:     for (j=ncl+1; j<=nch; j++) 
                   1908:       m[i][j]=m[i][j-1]+nlay;
                   1909:   }
                   1910:   return m; 
                   1911:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1912:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1913:   */
                   1914: }
                   1915: 
                   1916: /*************************free ma3x ************************/
                   1917: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1918: {
                   1919:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1920:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1921:   free((FREE_ARG)(m+nrl-NR_END));
                   1922: }
                   1923: 
                   1924: /*************** function subdirf ***********/
                   1925: char *subdirf(char fileres[])
                   1926: {
                   1927:   /* Caution optionfilefiname is hidden */
                   1928:   strcpy(tmpout,optionfilefiname);
                   1929:   strcat(tmpout,"/"); /* Add to the right */
                   1930:   strcat(tmpout,fileres);
                   1931:   return tmpout;
                   1932: }
                   1933: 
                   1934: /*************** function subdirf2 ***********/
                   1935: char *subdirf2(char fileres[], char *preop)
                   1936: {
1.314     brouard  1937:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1938:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1939:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1940:   /* Caution optionfilefiname is hidden */
                   1941:   strcpy(tmpout,optionfilefiname);
                   1942:   strcat(tmpout,"/");
                   1943:   strcat(tmpout,preop);
                   1944:   strcat(tmpout,fileres);
                   1945:   return tmpout;
                   1946: }
                   1947: 
                   1948: /*************** function subdirf3 ***********/
                   1949: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1950: {
                   1951:   
                   1952:   /* Caution optionfilefiname is hidden */
                   1953:   strcpy(tmpout,optionfilefiname);
                   1954:   strcat(tmpout,"/");
                   1955:   strcat(tmpout,preop);
                   1956:   strcat(tmpout,preop2);
                   1957:   strcat(tmpout,fileres);
                   1958:   return tmpout;
                   1959: }
1.213     brouard  1960:  
                   1961: /*************** function subdirfext ***********/
                   1962: char *subdirfext(char fileres[], char *preop, char *postop)
                   1963: {
                   1964:   
                   1965:   strcpy(tmpout,preop);
                   1966:   strcat(tmpout,fileres);
                   1967:   strcat(tmpout,postop);
                   1968:   return tmpout;
                   1969: }
1.126     brouard  1970: 
1.213     brouard  1971: /*************** function subdirfext3 ***********/
                   1972: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1973: {
                   1974:   
                   1975:   /* Caution optionfilefiname is hidden */
                   1976:   strcpy(tmpout,optionfilefiname);
                   1977:   strcat(tmpout,"/");
                   1978:   strcat(tmpout,preop);
                   1979:   strcat(tmpout,fileres);
                   1980:   strcat(tmpout,postop);
                   1981:   return tmpout;
                   1982: }
                   1983:  
1.162     brouard  1984: char *asc_diff_time(long time_sec, char ascdiff[])
                   1985: {
                   1986:   long sec_left, days, hours, minutes;
                   1987:   days = (time_sec) / (60*60*24);
                   1988:   sec_left = (time_sec) % (60*60*24);
                   1989:   hours = (sec_left) / (60*60) ;
                   1990:   sec_left = (sec_left) %(60*60);
                   1991:   minutes = (sec_left) /60;
                   1992:   sec_left = (sec_left) % (60);
                   1993:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1994:   return ascdiff;
                   1995: }
                   1996: 
1.126     brouard  1997: /***************** f1dim *************************/
                   1998: extern int ncom; 
                   1999: extern double *pcom,*xicom;
                   2000: extern double (*nrfunc)(double []); 
                   2001:  
                   2002: double f1dim(double x) 
                   2003: { 
                   2004:   int j; 
                   2005:   double f;
                   2006:   double *xt; 
                   2007:  
                   2008:   xt=vector(1,ncom); 
                   2009:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2010:   f=(*nrfunc)(xt); 
                   2011:   free_vector(xt,1,ncom); 
                   2012:   return f; 
                   2013: } 
                   2014: 
                   2015: /*****************brent *************************/
                   2016: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2017: {
                   2018:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2019:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2020:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2021:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2022:    * returned function value. 
                   2023:   */
1.126     brouard  2024:   int iter; 
                   2025:   double a,b,d,etemp;
1.159     brouard  2026:   double fu=0,fv,fw,fx;
1.164     brouard  2027:   double ftemp=0.;
1.126     brouard  2028:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2029:   double e=0.0; 
                   2030:  
                   2031:   a=(ax < cx ? ax : cx); 
                   2032:   b=(ax > cx ? ax : cx); 
                   2033:   x=w=v=bx; 
                   2034:   fw=fv=fx=(*f)(x); 
                   2035:   for (iter=1;iter<=ITMAX;iter++) { 
                   2036:     xm=0.5*(a+b); 
                   2037:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2038:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2039:     printf(".");fflush(stdout);
                   2040:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2041: #ifdef DEBUGBRENT
1.126     brouard  2042:     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);
                   2043:     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);
                   2044:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2045: #endif
                   2046:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2047:       *xmin=x; 
                   2048:       return fx; 
                   2049:     } 
                   2050:     ftemp=fu;
                   2051:     if (fabs(e) > tol1) { 
                   2052:       r=(x-w)*(fx-fv); 
                   2053:       q=(x-v)*(fx-fw); 
                   2054:       p=(x-v)*q-(x-w)*r; 
                   2055:       q=2.0*(q-r); 
                   2056:       if (q > 0.0) p = -p; 
                   2057:       q=fabs(q); 
                   2058:       etemp=e; 
                   2059:       e=d; 
                   2060:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2061:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2062:       else { 
1.224     brouard  2063:                                d=p/q; 
                   2064:                                u=x+d; 
                   2065:                                if (u-a < tol2 || b-u < tol2) 
                   2066:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2067:       } 
                   2068:     } else { 
                   2069:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2070:     } 
                   2071:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2072:     fu=(*f)(u); 
                   2073:     if (fu <= fx) { 
                   2074:       if (u >= x) a=x; else b=x; 
                   2075:       SHFT(v,w,x,u) 
1.183     brouard  2076:       SHFT(fv,fw,fx,fu) 
                   2077:     } else { 
                   2078:       if (u < x) a=u; else b=u; 
                   2079:       if (fu <= fw || w == x) { 
1.224     brouard  2080:                                v=w; 
                   2081:                                w=u; 
                   2082:                                fv=fw; 
                   2083:                                fw=fu; 
1.183     brouard  2084:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2085:                                v=u; 
                   2086:                                fv=fu; 
1.183     brouard  2087:       } 
                   2088:     } 
1.126     brouard  2089:   } 
                   2090:   nrerror("Too many iterations in brent"); 
                   2091:   *xmin=x; 
                   2092:   return fx; 
                   2093: } 
                   2094: 
                   2095: /****************** mnbrak ***********************/
                   2096: 
                   2097: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2098:            double (*func)(double)) 
1.183     brouard  2099: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2100: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2101: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2102: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2103:    */
1.126     brouard  2104:   double ulim,u,r,q, dum;
                   2105:   double fu; 
1.187     brouard  2106: 
                   2107:   double scale=10.;
                   2108:   int iterscale=0;
                   2109: 
                   2110:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2111:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2112: 
                   2113: 
                   2114:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2115:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2116:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2117:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2118:   /* } */
                   2119: 
1.126     brouard  2120:   if (*fb > *fa) { 
                   2121:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2122:     SHFT(dum,*fb,*fa,dum) 
                   2123:   } 
1.126     brouard  2124:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2125:   *fc=(*func)(*cx); 
1.183     brouard  2126: #ifdef DEBUG
1.224     brouard  2127:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2128:   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  2129: #endif
1.224     brouard  2130:   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  2131:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2132:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2133:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2134:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2135:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2136:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2137:       fu=(*func)(u); 
1.163     brouard  2138: #ifdef DEBUG
                   2139:       /* f(x)=A(x-u)**2+f(u) */
                   2140:       double A, fparabu; 
                   2141:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2142:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2143:       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);
                   2144:       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  2145:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2146:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2147:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2148:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2149: #endif 
1.184     brouard  2150: #ifdef MNBRAKORIGINAL
1.183     brouard  2151: #else
1.191     brouard  2152: /*       if (fu > *fc) { */
                   2153: /* #ifdef DEBUG */
                   2154: /*       printf("mnbrak4  fu > fc \n"); */
                   2155: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2156: /* #endif */
                   2157: /*     /\* 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 *\\/  *\/ */
                   2158: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2159: /*     dum=u; /\* Shifting c and u *\/ */
                   2160: /*     u = *cx; */
                   2161: /*     *cx = dum; */
                   2162: /*     dum = fu; */
                   2163: /*     fu = *fc; */
                   2164: /*     *fc =dum; */
                   2165: /*       } else { /\* end *\/ */
                   2166: /* #ifdef DEBUG */
                   2167: /*       printf("mnbrak3  fu < fc \n"); */
                   2168: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2169: /* #endif */
                   2170: /*     dum=u; /\* Shifting c and u *\/ */
                   2171: /*     u = *cx; */
                   2172: /*     *cx = dum; */
                   2173: /*     dum = fu; */
                   2174: /*     fu = *fc; */
                   2175: /*     *fc =dum; */
                   2176: /*       } */
1.224     brouard  2177: #ifdef DEBUGMNBRAK
                   2178:                 double A, fparabu; 
                   2179:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2180:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2181:      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);
                   2182:      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  2183: #endif
1.191     brouard  2184:       dum=u; /* Shifting c and u */
                   2185:       u = *cx;
                   2186:       *cx = dum;
                   2187:       dum = fu;
                   2188:       fu = *fc;
                   2189:       *fc =dum;
1.183     brouard  2190: #endif
1.162     brouard  2191:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2192: #ifdef DEBUG
1.224     brouard  2193:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2194:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2195: #endif
1.126     brouard  2196:       fu=(*func)(u); 
                   2197:       if (fu < *fc) { 
1.183     brouard  2198: #ifdef DEBUG
1.224     brouard  2199:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2200:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2201: #endif
                   2202:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2203:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2204: #ifdef DEBUG
                   2205:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2206: #endif
                   2207:       } 
1.162     brouard  2208:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2209: #ifdef DEBUG
1.224     brouard  2210:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2211:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2212: #endif
1.126     brouard  2213:       u=ulim; 
                   2214:       fu=(*func)(u); 
1.183     brouard  2215:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2216: #ifdef DEBUG
1.224     brouard  2217:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2218:       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  2219: #endif
1.126     brouard  2220:       u=(*cx)+GOLD*(*cx-*bx); 
                   2221:       fu=(*func)(u); 
1.224     brouard  2222: #ifdef DEBUG
                   2223:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2224:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2225: #endif
1.183     brouard  2226:     } /* end tests */
1.126     brouard  2227:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2228:     SHFT(*fa,*fb,*fc,fu) 
                   2229: #ifdef DEBUG
1.224     brouard  2230:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2231:       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  2232: #endif
                   2233:   } /* 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  2234: } 
                   2235: 
                   2236: /*************** linmin ************************/
1.162     brouard  2237: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2238: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2239: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2240: the value of func at the returned location p . This is actually all accomplished by calling the
                   2241: routines mnbrak and brent .*/
1.126     brouard  2242: int ncom; 
                   2243: double *pcom,*xicom;
                   2244: double (*nrfunc)(double []); 
                   2245:  
1.224     brouard  2246: #ifdef LINMINORIGINAL
1.126     brouard  2247: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2248: #else
                   2249: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2250: #endif
1.126     brouard  2251: { 
                   2252:   double brent(double ax, double bx, double cx, 
                   2253:               double (*f)(double), double tol, double *xmin); 
                   2254:   double f1dim(double x); 
                   2255:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2256:              double *fc, double (*func)(double)); 
                   2257:   int j; 
                   2258:   double xx,xmin,bx,ax; 
                   2259:   double fx,fb,fa;
1.187     brouard  2260: 
1.203     brouard  2261: #ifdef LINMINORIGINAL
                   2262: #else
                   2263:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2264: #endif
                   2265:   
1.126     brouard  2266:   ncom=n; 
                   2267:   pcom=vector(1,n); 
                   2268:   xicom=vector(1,n); 
                   2269:   nrfunc=func; 
                   2270:   for (j=1;j<=n;j++) { 
                   2271:     pcom[j]=p[j]; 
1.202     brouard  2272:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2273:   } 
1.187     brouard  2274: 
1.203     brouard  2275: #ifdef LINMINORIGINAL
                   2276:   xx=1.;
                   2277: #else
                   2278:   axs=0.0;
                   2279:   xxs=1.;
                   2280:   do{
                   2281:     xx= xxs;
                   2282: #endif
1.187     brouard  2283:     ax=0.;
                   2284:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2285:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2286:     /* 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))   */
                   2287:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2288:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2289:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2290:     /* 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  2291: #ifdef LINMINORIGINAL
                   2292: #else
                   2293:     if (fx != fx){
1.224     brouard  2294:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2295:                        printf("|");
                   2296:                        fprintf(ficlog,"|");
1.203     brouard  2297: #ifdef DEBUGLINMIN
1.224     brouard  2298:                        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  2299: #endif
                   2300:     }
1.224     brouard  2301:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2302: #endif
                   2303:   
1.191     brouard  2304: #ifdef DEBUGLINMIN
                   2305:   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  2306:   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  2307: #endif
1.224     brouard  2308: #ifdef LINMINORIGINAL
                   2309: #else
1.317     brouard  2310:   if(fb == fx){ /* Flat function in the direction */
                   2311:     xmin=xx;
1.224     brouard  2312:     *flat=1;
1.317     brouard  2313:   }else{
1.224     brouard  2314:     *flat=0;
                   2315: #endif
                   2316:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2317:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2318:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2319:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2320:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2321:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2322: #ifdef DEBUG
1.224     brouard  2323:   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);
                   2324:   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);
                   2325: #endif
                   2326: #ifdef LINMINORIGINAL
                   2327: #else
                   2328:                        }
1.126     brouard  2329: #endif
1.191     brouard  2330: #ifdef DEBUGLINMIN
                   2331:   printf("linmin end ");
1.202     brouard  2332:   fprintf(ficlog,"linmin end ");
1.191     brouard  2333: #endif
1.126     brouard  2334:   for (j=1;j<=n;j++) { 
1.203     brouard  2335: #ifdef LINMINORIGINAL
                   2336:     xi[j] *= xmin; 
                   2337: #else
                   2338: #ifdef DEBUGLINMIN
                   2339:     if(xxs <1.0)
                   2340:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2341: #endif
                   2342:     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) */
                   2343: #ifdef DEBUGLINMIN
                   2344:     if(xxs <1.0)
                   2345:       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 );
                   2346: #endif
                   2347: #endif
1.187     brouard  2348:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2349:   } 
1.191     brouard  2350: #ifdef DEBUGLINMIN
1.203     brouard  2351:   printf("\n");
1.191     brouard  2352:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2353:   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  2354:   for (j=1;j<=n;j++) { 
1.202     brouard  2355:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2356:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2357:     if(j % ncovmodel == 0){
1.191     brouard  2358:       printf("\n");
1.202     brouard  2359:       fprintf(ficlog,"\n");
                   2360:     }
1.191     brouard  2361:   }
1.203     brouard  2362: #else
1.191     brouard  2363: #endif
1.126     brouard  2364:   free_vector(xicom,1,n); 
                   2365:   free_vector(pcom,1,n); 
                   2366: } 
                   2367: 
                   2368: 
                   2369: /*************** powell ************************/
1.162     brouard  2370: /*
1.317     brouard  2371: Minimization of a function func of n variables. Input consists in an initial starting point
                   2372: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2373: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2374: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2375: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2376: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2377:  */
1.224     brouard  2378: #ifdef LINMINORIGINAL
                   2379: #else
                   2380:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2381:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2382: #endif
1.126     brouard  2383: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2384:            double (*func)(double [])) 
                   2385: { 
1.224     brouard  2386: #ifdef LINMINORIGINAL
                   2387:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2388:              double (*func)(double [])); 
1.224     brouard  2389: #else 
1.241     brouard  2390:  void linmin(double p[], double xi[], int n, double *fret,
                   2391:             double (*func)(double []),int *flat); 
1.224     brouard  2392: #endif
1.239     brouard  2393:  int i,ibig,j,jk,k; 
1.126     brouard  2394:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2395:   double directest;
1.126     brouard  2396:   double fp,fptt;
                   2397:   double *xits;
                   2398:   int niterf, itmp;
                   2399: 
                   2400:   pt=vector(1,n); 
                   2401:   ptt=vector(1,n); 
                   2402:   xit=vector(1,n); 
                   2403:   xits=vector(1,n); 
                   2404:   *fret=(*func)(p); 
                   2405:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2406:   rcurr_time = time(NULL);  
1.126     brouard  2407:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2408:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2409:     ibig=0; 
                   2410:     del=0.0; 
1.157     brouard  2411:     rlast_time=rcurr_time;
                   2412:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2413:     rcurr_time = time(NULL);  
                   2414:     curr_time = *localtime(&rcurr_time);
                   2415:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2416:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2417: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2418:     for (i=1;i<=n;i++) {
1.126     brouard  2419:       fprintf(ficrespow," %.12lf", p[i]);
                   2420:     }
1.239     brouard  2421:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2422:     printf("\n#model=  1      +     age ");
                   2423:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2424:     if(nagesqr==1){
1.241     brouard  2425:        printf("  + age*age  ");
                   2426:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2427:     }
                   2428:     for(j=1;j <=ncovmodel-2;j++){
                   2429:       if(Typevar[j]==0) {
                   2430:        printf("  +      V%d  ",Tvar[j]);
                   2431:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2432:       }else if(Typevar[j]==1) {
                   2433:        printf("  +    V%d*age ",Tvar[j]);
                   2434:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2435:       }else if(Typevar[j]==2) {
                   2436:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2437:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2438:       }
                   2439:     }
1.126     brouard  2440:     printf("\n");
1.239     brouard  2441: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2442: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2443:     fprintf(ficlog,"\n");
1.239     brouard  2444:     for(i=1,jk=1; i <=nlstate; i++){
                   2445:       for(k=1; k <=(nlstate+ndeath); k++){
                   2446:        if (k != i) {
                   2447:          printf("%d%d ",i,k);
                   2448:          fprintf(ficlog,"%d%d ",i,k);
                   2449:          for(j=1; j <=ncovmodel; j++){
                   2450:            printf("%12.7f ",p[jk]);
                   2451:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2452:            jk++; 
                   2453:          }
                   2454:          printf("\n");
                   2455:          fprintf(ficlog,"\n");
                   2456:        }
                   2457:       }
                   2458:     }
1.241     brouard  2459:     if(*iter <=3 && *iter >1){
1.157     brouard  2460:       tml = *localtime(&rcurr_time);
                   2461:       strcpy(strcurr,asctime(&tml));
                   2462:       rforecast_time=rcurr_time; 
1.126     brouard  2463:       itmp = strlen(strcurr);
                   2464:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2465:        strcurr[itmp-1]='\0';
1.162     brouard  2466:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2467:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2468:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2469:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2470:        forecast_time = *localtime(&rforecast_time);
                   2471:        strcpy(strfor,asctime(&forecast_time));
                   2472:        itmp = strlen(strfor);
                   2473:        if(strfor[itmp-1]=='\n')
                   2474:          strfor[itmp-1]='\0';
                   2475:        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);
                   2476:        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  2477:       }
                   2478:     }
1.187     brouard  2479:     for (i=1;i<=n;i++) { /* For each direction i */
                   2480:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2481:       fptt=(*fret); 
                   2482: #ifdef DEBUG
1.203     brouard  2483:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2484:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2485: #endif
1.203     brouard  2486:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2487:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2488: #ifdef LINMINORIGINAL
1.188     brouard  2489:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2490: #else
                   2491:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2492:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2493: #endif
                   2494:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2495:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2496:                                /* because that direction will be replaced unless the gain del is small */
                   2497:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2498:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2499:                                /* with the new direction. */
                   2500:                                del=fabs(fptt-(*fret)); 
                   2501:                                ibig=i; 
1.126     brouard  2502:       } 
                   2503: #ifdef DEBUG
                   2504:       printf("%d %.12e",i,(*fret));
                   2505:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2506:       for (j=1;j<=n;j++) {
1.224     brouard  2507:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2508:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2509:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2510:       }
                   2511:       for(j=1;j<=n;j++) {
1.225     brouard  2512:                                printf(" p(%d)=%.12e",j,p[j]);
                   2513:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2514:       }
                   2515:       printf("\n");
                   2516:       fprintf(ficlog,"\n");
                   2517: #endif
1.187     brouard  2518:     } /* end loop on each direction i */
                   2519:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2520:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2521:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2522:     for(j=1;j<=n;j++) {
                   2523:       if(flatdir[j] >0){
                   2524:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2525:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2526:       }
1.319     brouard  2527:       /* printf("\n"); */
                   2528:       /* fprintf(ficlog,"\n"); */
                   2529:     }
1.243     brouard  2530:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2531:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2532:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2533:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2534:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2535:       /* decreased of more than 3.84  */
                   2536:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2537:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2538:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2539:                        
1.188     brouard  2540:       /* Starting the program with initial values given by a former maximization will simply change */
                   2541:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2542:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2543:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2544: #ifdef DEBUG
                   2545:       int k[2],l;
                   2546:       k[0]=1;
                   2547:       k[1]=-1;
                   2548:       printf("Max: %.12e",(*func)(p));
                   2549:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2550:       for (j=1;j<=n;j++) {
                   2551:        printf(" %.12e",p[j]);
                   2552:        fprintf(ficlog," %.12e",p[j]);
                   2553:       }
                   2554:       printf("\n");
                   2555:       fprintf(ficlog,"\n");
                   2556:       for(l=0;l<=1;l++) {
                   2557:        for (j=1;j<=n;j++) {
                   2558:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2559:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2560:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2561:        }
                   2562:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2563:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2564:       }
                   2565: #endif
                   2566: 
                   2567:       free_vector(xit,1,n); 
                   2568:       free_vector(xits,1,n); 
                   2569:       free_vector(ptt,1,n); 
                   2570:       free_vector(pt,1,n); 
                   2571:       return; 
1.192     brouard  2572:     } /* enough precision */ 
1.240     brouard  2573:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2574:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2575:       ptt[j]=2.0*p[j]-pt[j]; 
                   2576:       xit[j]=p[j]-pt[j]; 
                   2577:       pt[j]=p[j]; 
                   2578:     } 
1.181     brouard  2579:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2580: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2581:                if (*iter <=4) {
1.225     brouard  2582: #else
                   2583: #endif
1.224     brouard  2584: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2585: #else
1.161     brouard  2586:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2587: #endif
1.162     brouard  2588:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2589:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2590:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2591:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2592:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2593:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2594:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2595:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2596:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2597:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2598:       /* mu² and del² are equal when f3=f1 */
                   2599:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2600:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2601:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2602:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2603: #ifdef NRCORIGINAL
                   2604:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2605: #else
                   2606:       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  2607:       t= t- del*SQR(fp-fptt);
1.183     brouard  2608: #endif
1.202     brouard  2609:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2610: #ifdef DEBUG
1.181     brouard  2611:       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);
                   2612:       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  2613:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2614:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2615:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2616:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2617:       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);
                   2618:       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);
                   2619: #endif
1.183     brouard  2620: #ifdef POWELLORIGINAL
                   2621:       if (t < 0.0) { /* Then we use it for new direction */
                   2622: #else
1.182     brouard  2623:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2624:                                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  2625:         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  2626:         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  2627:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2628:       } 
1.181     brouard  2629:       if (directest < 0.0) { /* Then we use it for new direction */
                   2630: #endif
1.191     brouard  2631: #ifdef DEBUGLINMIN
1.234     brouard  2632:        printf("Before linmin in direction P%d-P0\n",n);
                   2633:        for (j=1;j<=n;j++) {
                   2634:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2635:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2636:          if(j % ncovmodel == 0){
                   2637:            printf("\n");
                   2638:            fprintf(ficlog,"\n");
                   2639:          }
                   2640:        }
1.224     brouard  2641: #endif
                   2642: #ifdef LINMINORIGINAL
1.234     brouard  2643:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2644: #else
1.234     brouard  2645:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2646:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2647: #endif
1.234     brouard  2648:        
1.191     brouard  2649: #ifdef DEBUGLINMIN
1.234     brouard  2650:        for (j=1;j<=n;j++) { 
                   2651:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2652:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2653:          if(j % ncovmodel == 0){
                   2654:            printf("\n");
                   2655:            fprintf(ficlog,"\n");
                   2656:          }
                   2657:        }
1.224     brouard  2658: #endif
1.234     brouard  2659:        for (j=1;j<=n;j++) { 
                   2660:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2661:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2662:        }
1.224     brouard  2663: #ifdef LINMINORIGINAL
                   2664: #else
1.234     brouard  2665:        for (j=1, flatd=0;j<=n;j++) {
                   2666:          if(flatdir[j]>0)
                   2667:            flatd++;
                   2668:        }
                   2669:        if(flatd >0){
1.255     brouard  2670:          printf("%d flat directions: ",flatd);
                   2671:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2672:          for (j=1;j<=n;j++) { 
                   2673:            if(flatdir[j]>0){
                   2674:              printf("%d ",j);
                   2675:              fprintf(ficlog,"%d ",j);
                   2676:            }
                   2677:          }
                   2678:          printf("\n");
                   2679:          fprintf(ficlog,"\n");
1.319     brouard  2680: #ifdef FLATSUP
                   2681:           free_vector(xit,1,n); 
                   2682:           free_vector(xits,1,n); 
                   2683:           free_vector(ptt,1,n); 
                   2684:           free_vector(pt,1,n); 
                   2685:           return;
                   2686: #endif
1.234     brouard  2687:        }
1.191     brouard  2688: #endif
1.234     brouard  2689:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2690:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2691:        
1.126     brouard  2692: #ifdef DEBUG
1.234     brouard  2693:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2694:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2695:        for(j=1;j<=n;j++){
                   2696:          printf(" %lf",xit[j]);
                   2697:          fprintf(ficlog," %lf",xit[j]);
                   2698:        }
                   2699:        printf("\n");
                   2700:        fprintf(ficlog,"\n");
1.126     brouard  2701: #endif
1.192     brouard  2702:       } /* end of t or directest negative */
1.224     brouard  2703: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2704: #else
1.234     brouard  2705:       } /* end if (fptt < fp)  */
1.192     brouard  2706: #endif
1.225     brouard  2707: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2708:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2709: #else
1.224     brouard  2710: #endif
1.234     brouard  2711:                } /* loop iteration */ 
1.126     brouard  2712: } 
1.234     brouard  2713:   
1.126     brouard  2714: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2715:   
1.235     brouard  2716:   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  2717:   {
1.279     brouard  2718:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2719:      *   (and selected quantitative values in nres)
                   2720:      *  by left multiplying the unit
                   2721:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2722:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2723:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2724:      * or prevalence in state 1, prevalence in state 2, 0
                   2725:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2726:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2727:      * Output is prlim.
                   2728:      * Initial matrix pimij 
                   2729:      */
1.206     brouard  2730:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2731:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2732:   /*  0,                   0                  , 1} */
                   2733:   /*
                   2734:    * and after some iteration: */
                   2735:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2736:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2737:   /*  0,                   0                  , 1} */
                   2738:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2739:   /* {0.51571254859325999, 0.4842874514067399, */
                   2740:   /*  0.51326036147820708, 0.48673963852179264} */
                   2741:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2742:     
1.126     brouard  2743:   int i, ii,j,k;
1.209     brouard  2744:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2745:   /* double **matprod2(); */ /* test */
1.218     brouard  2746:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2747:   double **newm;
1.209     brouard  2748:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2749:   int ncvloop=0;
1.288     brouard  2750:   int first=0;
1.169     brouard  2751:   
1.209     brouard  2752:   min=vector(1,nlstate);
                   2753:   max=vector(1,nlstate);
                   2754:   meandiff=vector(1,nlstate);
                   2755: 
1.218     brouard  2756:        /* Starting with matrix unity */
1.126     brouard  2757:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2758:     for (j=1;j<=nlstate+ndeath;j++){
                   2759:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2760:     }
1.169     brouard  2761:   
                   2762:   cov[1]=1.;
                   2763:   
                   2764:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2765:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2766:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2767:     ncvloop++;
1.126     brouard  2768:     newm=savm;
                   2769:     /* Covariates have to be included here again */
1.138     brouard  2770:     cov[2]=agefin;
1.319     brouard  2771:      if(nagesqr==1){
                   2772:       cov[3]= agefin*agefin;
                   2773:      }
1.234     brouard  2774:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2775:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2776:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.319     brouard  2777:       /* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; */
1.235     brouard  2778:       /* 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)); */
1.234     brouard  2779:     }
                   2780:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2781:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  2782:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
                   2783:       /* cov[++k1]=Tqresult[nres][k];  */
1.235     brouard  2784:       /* 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]); */
1.138     brouard  2785:     }
1.237     brouard  2786:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2787:       if(Dummy[Tage[k]]==2){ /* dummy with age */
1.234     brouard  2788:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  2789:        /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2790:       } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
                   2791:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
                   2792:        /* cov[++k1]=Tqresult[nres][k];  */
1.234     brouard  2793:       }
1.235     brouard  2794:       /* 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]); */
1.234     brouard  2795:     }
1.237     brouard  2796:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2797:       /* 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]); */
1.237     brouard  2798:       if(Dummy[Tvard[k][1]==0]){
                   2799:        if(Dummy[Tvard[k][2]==0]){
                   2800:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.319     brouard  2801:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.237     brouard  2802:        }else{
                   2803:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
1.319     brouard  2804:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
1.237     brouard  2805:        }
                   2806:       }else{
                   2807:        if(Dummy[Tvard[k][2]==0]){
                   2808:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
1.319     brouard  2809:          /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
1.237     brouard  2810:        }else{
                   2811:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
1.319     brouard  2812:          /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
1.237     brouard  2813:        }
                   2814:       }
1.234     brouard  2815:     }
1.138     brouard  2816:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2817:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2818:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2819:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2820:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2821:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2822:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2823:     
1.126     brouard  2824:     savm=oldm;
                   2825:     oldm=newm;
1.209     brouard  2826: 
                   2827:     for(j=1; j<=nlstate; j++){
                   2828:       max[j]=0.;
                   2829:       min[j]=1.;
                   2830:     }
                   2831:     for(i=1;i<=nlstate;i++){
                   2832:       sumnew=0;
                   2833:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2834:       for(j=1; j<=nlstate; j++){ 
                   2835:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2836:        max[j]=FMAX(max[j],prlim[i][j]);
                   2837:        min[j]=FMIN(min[j],prlim[i][j]);
                   2838:       }
                   2839:     }
                   2840: 
1.126     brouard  2841:     maxmax=0.;
1.209     brouard  2842:     for(j=1; j<=nlstate; j++){
                   2843:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2844:       maxmax=FMAX(maxmax,meandiff[j]);
                   2845:       /* 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  2846:     } /* j loop */
1.203     brouard  2847:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2848:     /* 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  2849:     if(maxmax < ftolpl){
1.209     brouard  2850:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2851:       free_vector(min,1,nlstate);
                   2852:       free_vector(max,1,nlstate);
                   2853:       free_vector(meandiff,1,nlstate);
1.126     brouard  2854:       return prlim;
                   2855:     }
1.288     brouard  2856:   } /* agefin loop */
1.208     brouard  2857:     /* After some age loop it doesn't converge */
1.288     brouard  2858:   if(!first){
                   2859:     first=1;
                   2860:     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  2861:     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);
                   2862:   }else if (first >=1 && first <10){
                   2863:     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);
                   2864:     first++;
                   2865:   }else if (first ==10){
                   2866:     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);
                   2867:     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");
                   2868:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2869:     first++;
1.288     brouard  2870:   }
                   2871: 
1.209     brouard  2872:   /* 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); */
                   2873:   free_vector(min,1,nlstate);
                   2874:   free_vector(max,1,nlstate);
                   2875:   free_vector(meandiff,1,nlstate);
1.208     brouard  2876:   
1.169     brouard  2877:   return prlim; /* should not reach here */
1.126     brouard  2878: }
                   2879: 
1.217     brouard  2880: 
                   2881:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2882: 
1.218     brouard  2883:  /* 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) */
                   2884:  /* 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  2885:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2886: {
1.264     brouard  2887:   /* 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  2888:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2889:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2890:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2891:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2892:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2893:   /* Initial matrix pimij */
                   2894:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2895:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2896:   /*  0,                   0                  , 1} */
                   2897:   /*
                   2898:    * and after some iteration: */
                   2899:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2900:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2901:   /*  0,                   0                  , 1} */
                   2902:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2903:   /* {0.51571254859325999, 0.4842874514067399, */
                   2904:   /*  0.51326036147820708, 0.48673963852179264} */
                   2905:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2906: 
                   2907:   int i, ii,j,k;
1.247     brouard  2908:   int first=0;
1.217     brouard  2909:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2910:   /* double **matprod2(); */ /* test */
                   2911:   double **out, cov[NCOVMAX+1], **bmij();
                   2912:   double **newm;
1.218     brouard  2913:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2914:   double        **oldm, **savm;  /* for use */
                   2915: 
1.217     brouard  2916:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2917:   int ncvloop=0;
                   2918:   
                   2919:   min=vector(1,nlstate);
                   2920:   max=vector(1,nlstate);
                   2921:   meandiff=vector(1,nlstate);
                   2922: 
1.266     brouard  2923:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2924:   oldm=oldms; savm=savms;
                   2925:   
                   2926:   /* Starting with matrix unity */
                   2927:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2928:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2929:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2930:     }
                   2931:   
                   2932:   cov[1]=1.;
                   2933:   
                   2934:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2935:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2936:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2937:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2938:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2939:     ncvloop++;
1.218     brouard  2940:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2941:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2942:     /* Covariates have to be included here again */
                   2943:     cov[2]=agefin;
1.319     brouard  2944:     if(nagesqr==1){
1.217     brouard  2945:       cov[3]= agefin*agefin;;
1.319     brouard  2946:     }
1.242     brouard  2947:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2948:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2949:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2950:       /* 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)); */
1.242     brouard  2951:     }
                   2952:     /* for (k=1; k<=cptcovn;k++) { */
                   2953:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2954:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2955:     /*   /\* 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])]); *\/ */
                   2956:     /* } */
                   2957:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2958:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2959:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2960:       /* 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]); */
                   2961:     }
                   2962:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2963:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2964:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2965:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2966:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2967:       /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ ERROR ???*/
                   2968:       if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.242     brouard  2969:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  2970:       } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   2971:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.242     brouard  2972:       }
                   2973:       /* 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]); */
                   2974:     }
                   2975:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2976:       /* 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]); */
                   2977:       if(Dummy[Tvard[k][1]==0]){
                   2978:        if(Dummy[Tvard[k][2]==0]){
                   2979:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2980:        }else{
                   2981:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2982:        }
                   2983:       }else{
                   2984:        if(Dummy[Tvard[k][2]==0]){
                   2985:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2986:        }else{
                   2987:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2988:        }
                   2989:       }
1.217     brouard  2990:     }
                   2991:     
                   2992:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2993:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2994:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2995:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2996:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2997:                /* ij should be linked to the correct index of cov */
                   2998:                /* age and covariate values ij are in 'cov', but we need to pass
                   2999:                 * ij for the observed prevalence at age and status and covariate
                   3000:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3001:                 */
                   3002:     /* 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 *\/ */
                   3003:     /* 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 *\/ */
                   3004:     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  3005:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3006:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3007:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3008:     /*         printf("%d newm= ",i); */
                   3009:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3010:     /*           printf("%f ",newm[i][j]); */
                   3011:     /*         } */
                   3012:     /*         printf("oldm * "); */
                   3013:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3014:     /*           printf("%f ",oldm[i][j]); */
                   3015:     /*         } */
1.268     brouard  3016:     /*         printf(" bmmij "); */
1.266     brouard  3017:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3018:     /*           printf("%f ",pmmij[i][j]); */
                   3019:     /*         } */
                   3020:     /*         printf("\n"); */
                   3021:     /*   } */
                   3022:     /* } */
1.217     brouard  3023:     savm=oldm;
                   3024:     oldm=newm;
1.266     brouard  3025: 
1.217     brouard  3026:     for(j=1; j<=nlstate; j++){
                   3027:       max[j]=0.;
                   3028:       min[j]=1.;
                   3029:     }
                   3030:     for(j=1; j<=nlstate; j++){ 
                   3031:       for(i=1;i<=nlstate;i++){
1.234     brouard  3032:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3033:        bprlim[i][j]= newm[i][j];
                   3034:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3035:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3036:       }
                   3037:     }
1.218     brouard  3038:                
1.217     brouard  3039:     maxmax=0.;
                   3040:     for(i=1; i<=nlstate; i++){
1.318     brouard  3041:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3042:       maxmax=FMAX(maxmax,meandiff[i]);
                   3043:       /* 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  3044:     } /* i loop */
1.217     brouard  3045:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3046:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3047:     if(maxmax < ftolpl){
1.220     brouard  3048:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3049:       free_vector(min,1,nlstate);
                   3050:       free_vector(max,1,nlstate);
                   3051:       free_vector(meandiff,1,nlstate);
                   3052:       return bprlim;
                   3053:     }
1.288     brouard  3054:   } /* agefin loop */
1.217     brouard  3055:     /* After some age loop it doesn't converge */
1.288     brouard  3056:   if(!first){
1.247     brouard  3057:     first=1;
                   3058:     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\
                   3059: 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);
                   3060:   }
                   3061:   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  3062: 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);
                   3063:   /* 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); */
                   3064:   free_vector(min,1,nlstate);
                   3065:   free_vector(max,1,nlstate);
                   3066:   free_vector(meandiff,1,nlstate);
                   3067:   
                   3068:   return bprlim; /* should not reach here */
                   3069: }
                   3070: 
1.126     brouard  3071: /*************** transition probabilities ***************/ 
                   3072: 
                   3073: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3074: {
1.138     brouard  3075:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3076:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3077:      model to the ncovmodel covariates (including constant and age).
                   3078:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3079:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3080:      ncth covariate in the global vector x is given by the formula:
                   3081:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3082:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3083:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3084:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3085:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3086:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3087:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3088:   */
                   3089:   double s1, lnpijopii;
1.126     brouard  3090:   /*double t34;*/
1.164     brouard  3091:   int i,j, nc, ii, jj;
1.126     brouard  3092: 
1.223     brouard  3093:   for(i=1; i<= nlstate; i++){
                   3094:     for(j=1; j<i;j++){
                   3095:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3096:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3097:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3098:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3099:       }
                   3100:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3101:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3102:     }
                   3103:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3104:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3105:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3106:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3107:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3108:       }
                   3109:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3110:     }
                   3111:   }
1.218     brouard  3112:   
1.223     brouard  3113:   for(i=1; i<= nlstate; i++){
                   3114:     s1=0;
                   3115:     for(j=1; j<i; j++){
                   3116:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3117:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3118:     }
                   3119:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3120:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3121:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3122:     }
                   3123:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3124:     ps[i][i]=1./(s1+1.);
                   3125:     /* Computing other pijs */
                   3126:     for(j=1; j<i; j++)
                   3127:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3128:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3129:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3130:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3131:   } /* end i */
1.218     brouard  3132:   
1.223     brouard  3133:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3134:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3135:       ps[ii][jj]=0;
                   3136:       ps[ii][ii]=1;
                   3137:     }
                   3138:   }
1.294     brouard  3139: 
                   3140: 
1.223     brouard  3141:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3142:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3143:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3144:   /*   } */
                   3145:   /*   printf("\n "); */
                   3146:   /* } */
                   3147:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3148:   /*
                   3149:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3150:                goto end;*/
1.266     brouard  3151:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3152: }
                   3153: 
1.218     brouard  3154: /*************** backward transition probabilities ***************/ 
                   3155: 
                   3156:  /* 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 ) */
                   3157: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3158:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3159: {
1.302     brouard  3160:   /* 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  3161:    * 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  3162:    */
1.218     brouard  3163:   int i, ii, j,k;
1.222     brouard  3164:   
                   3165:   double **out, **pmij();
                   3166:   double sumnew=0.;
1.218     brouard  3167:   double agefin;
1.292     brouard  3168:   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  3169:   double **dnewm, **dsavm, **doldm;
                   3170:   double **bbmij;
                   3171:   
1.218     brouard  3172:   doldm=ddoldms; /* global pointers */
1.222     brouard  3173:   dnewm=ddnewms;
                   3174:   dsavm=ddsavms;
1.318     brouard  3175: 
                   3176:   /* Debug */
                   3177:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3178:   agefin=cov[2];
1.268     brouard  3179:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3180:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3181:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3182:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3183: 
                   3184:   /* P_x */
1.266     brouard  3185:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3186:   /* outputs pmmij which is a stochastic matrix in row */
                   3187: 
                   3188:   /* Diag(w_x) */
1.292     brouard  3189:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3190:   sumnew=0.;
1.269     brouard  3191:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3192:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3193:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3194:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3195:   }
                   3196:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3197:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3198:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3199:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3200:     }
                   3201:   }else{
                   3202:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3203:       for (j=1;j<=nlstate+ndeath;j++)
                   3204:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3205:     }
                   3206:     /* if(sumnew <0.9){ */
                   3207:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3208:     /* } */
                   3209:   }
                   3210:   k3=0.0;  /* We put the last diagonal to 0 */
                   3211:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3212:       doldm[ii][ii]= k3;
                   3213:   }
                   3214:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3215:   
1.292     brouard  3216:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3217:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3218: 
1.292     brouard  3219:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3220:   /* 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  3221:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3222:     sumnew=0.;
1.222     brouard  3223:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3224:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3225:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3226:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3227:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3228:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3229:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3230:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3231:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3232:        /* }else */
1.268     brouard  3233:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3234:     } /*End ii */
                   3235:   } /* 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 */
                   3236: 
1.292     brouard  3237:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3238:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3239:   /* end bmij */
1.266     brouard  3240:   return ps; /*pointer is unchanged */
1.218     brouard  3241: }
1.217     brouard  3242: /*************** transition probabilities ***************/ 
                   3243: 
1.218     brouard  3244: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3245: {
                   3246:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3247:      computes the probability to be observed in state j being in state i by appying the
                   3248:      model to the ncovmodel covariates (including constant and age).
                   3249:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3250:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3251:      ncth covariate in the global vector x is given by the formula:
                   3252:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3253:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3254:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3255:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3256:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3257:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3258:   */
                   3259:   double s1, lnpijopii;
                   3260:   /*double t34;*/
                   3261:   int i,j, nc, ii, jj;
                   3262: 
1.234     brouard  3263:   for(i=1; i<= nlstate; i++){
                   3264:     for(j=1; j<i;j++){
                   3265:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3266:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3267:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3268:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3269:       }
                   3270:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3271:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3272:     }
                   3273:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3274:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3275:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3276:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3277:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3278:       }
                   3279:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3280:     }
                   3281:   }
                   3282:   
                   3283:   for(i=1; i<= nlstate; i++){
                   3284:     s1=0;
                   3285:     for(j=1; j<i; j++){
                   3286:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3287:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3288:     }
                   3289:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3290:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3291:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3292:     }
                   3293:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3294:     ps[i][i]=1./(s1+1.);
                   3295:     /* Computing other pijs */
                   3296:     for(j=1; j<i; j++)
                   3297:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3298:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3299:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3300:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3301:   } /* end i */
                   3302:   
                   3303:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3304:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3305:       ps[ii][jj]=0;
                   3306:       ps[ii][ii]=1;
                   3307:     }
                   3308:   }
1.296     brouard  3309:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3310:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3311:     s1=0.;
                   3312:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3313:       s1+=ps[ii][jj];
                   3314:     }
                   3315:     for(ii=1; ii<= nlstate; ii++){
                   3316:       ps[ii][jj]=ps[ii][jj]/s1;
                   3317:     }
                   3318:   }
                   3319:   /* Transposition */
                   3320:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3321:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3322:       s1=ps[ii][jj];
                   3323:       ps[ii][jj]=ps[jj][ii];
                   3324:       ps[jj][ii]=s1;
                   3325:     }
                   3326:   }
                   3327:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3328:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3329:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3330:   /*   } */
                   3331:   /*   printf("\n "); */
                   3332:   /* } */
                   3333:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3334:   /*
                   3335:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3336:     goto end;*/
                   3337:   return ps;
1.217     brouard  3338: }
                   3339: 
                   3340: 
1.126     brouard  3341: /**************** Product of 2 matrices ******************/
                   3342: 
1.145     brouard  3343: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3344: {
                   3345:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3346:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3347:   /* in, b, out are matrice of pointers which should have been initialized 
                   3348:      before: only the contents of out is modified. The function returns
                   3349:      a pointer to pointers identical to out */
1.145     brouard  3350:   int i, j, k;
1.126     brouard  3351:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3352:     for(k=ncolol; k<=ncoloh; k++){
                   3353:       out[i][k]=0.;
                   3354:       for(j=ncl; j<=nch; j++)
                   3355:        out[i][k] +=in[i][j]*b[j][k];
                   3356:     }
1.126     brouard  3357:   return out;
                   3358: }
                   3359: 
                   3360: 
                   3361: /************* Higher Matrix Product ***************/
                   3362: 
1.235     brouard  3363: 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  3364: {
1.218     brouard  3365:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3366:      'nhstepm*hstepm*stepm' months (i.e. until
                   3367:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3368:      nhstepm*hstepm matrices. 
                   3369:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3370:      (typically every 2 years instead of every month which is too big 
                   3371:      for the memory).
                   3372:      Model is determined by parameters x and covariates have to be 
                   3373:      included manually here. 
                   3374: 
                   3375:      */
                   3376: 
                   3377:   int i, j, d, h, k;
1.131     brouard  3378:   double **out, cov[NCOVMAX+1];
1.126     brouard  3379:   double **newm;
1.187     brouard  3380:   double agexact;
1.214     brouard  3381:   double agebegin, ageend;
1.126     brouard  3382: 
                   3383:   /* Hstepm could be zero and should return the unit matrix */
                   3384:   for (i=1;i<=nlstate+ndeath;i++)
                   3385:     for (j=1;j<=nlstate+ndeath;j++){
                   3386:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3387:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3388:     }
                   3389:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3390:   for(h=1; h <=nhstepm; h++){
                   3391:     for(d=1; d <=hstepm; d++){
                   3392:       newm=savm;
                   3393:       /* Covariates have to be included here again */
                   3394:       cov[1]=1.;
1.214     brouard  3395:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3396:       cov[2]=agexact;
1.319     brouard  3397:       if(nagesqr==1){
1.227     brouard  3398:        cov[3]= agexact*agexact;
1.319     brouard  3399:       }
1.235     brouard  3400:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
1.319     brouard  3401: /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3402:        /* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 */
                   3403: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3404: /*    k        1  2   3   4     5    6    7     8    9 */
                   3405: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   3406: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   3407: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   3408: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
1.235     brouard  3409:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3410:        /* printf("hpxij 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)); */
                   3411:       }
                   3412:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3413:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  3414:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
1.235     brouard  3415:        /* 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]); */
                   3416:       }
1.319     brouard  3417:       for (k=1; k<=cptcovage;k++){ /* For product with age V1+V1*age +V4 +age*V3 */
                   3418:        /* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*/
                   3419:        /* */
                   3420:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
                   3421:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ */
1.235     brouard  3422:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  3423:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   3424:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.235     brouard  3425:        }
                   3426:        /* 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]); */
                   3427:       }
1.319     brouard  3428:       for (k=1; k<=cptcovprod;k++){ /*  For product without age */
1.235     brouard  3429:        /* printf("hPxij 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]); */
1.319     brouard  3430:        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   3431:        if(Dummy[Tvard[k][1]==0]){
                   3432:          if(Dummy[Tvard[k][2]==0]){
                   3433:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3434:          }else{
                   3435:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   3436:          }
                   3437:        }else{
                   3438:          if(Dummy[Tvard[k][2]==0]){
                   3439:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   3440:          }else{
                   3441:            cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3442:          }
                   3443:        }
1.235     brouard  3444:       }
                   3445:       /* for (k=1; k<=cptcovn;k++)  */
                   3446:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3447:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3448:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3449:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3450:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3451:       
                   3452:       
1.126     brouard  3453:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3454:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3455:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3456:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3457:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3458:       /* if((int)age == 70){ */
                   3459:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3460:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3461:       /*         printf("%d pmmij ",i); */
                   3462:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3463:       /*           printf("%f ",pmmij[i][j]); */
                   3464:       /*         } */
                   3465:       /*         printf(" oldm "); */
                   3466:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3467:       /*           printf("%f ",oldm[i][j]); */
                   3468:       /*         } */
                   3469:       /*         printf("\n"); */
                   3470:       /*       } */
                   3471:       /* } */
1.126     brouard  3472:       savm=oldm;
                   3473:       oldm=newm;
                   3474:     }
                   3475:     for(i=1; i<=nlstate+ndeath; i++)
                   3476:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3477:        po[i][j][h]=newm[i][j];
                   3478:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3479:       }
1.128     brouard  3480:     /*printf("h=%d ",h);*/
1.126     brouard  3481:   } /* end h */
1.267     brouard  3482:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3483:   return po;
                   3484: }
                   3485: 
1.217     brouard  3486: /************* Higher Back Matrix Product ***************/
1.218     brouard  3487: /* 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  3488: 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  3489: {
1.266     brouard  3490:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3491:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3492:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3493:      nhstepm*hstepm matrices.
                   3494:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3495:      (typically every 2 years instead of every month which is too big
1.217     brouard  3496:      for the memory).
1.218     brouard  3497:      Model is determined by parameters x and covariates have to be
1.266     brouard  3498:      included manually here. Then we use a call to bmij(x and cov)
                   3499:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3500:   */
1.217     brouard  3501: 
                   3502:   int i, j, d, h, k;
1.266     brouard  3503:   double **out, cov[NCOVMAX+1], **bmij();
                   3504:   double **newm, ***newmm;
1.217     brouard  3505:   double agexact;
                   3506:   double agebegin, ageend;
1.222     brouard  3507:   double **oldm, **savm;
1.217     brouard  3508: 
1.266     brouard  3509:   newmm=po; /* To be saved */
                   3510:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3511:   /* Hstepm could be zero and should return the unit matrix */
                   3512:   for (i=1;i<=nlstate+ndeath;i++)
                   3513:     for (j=1;j<=nlstate+ndeath;j++){
                   3514:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3515:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3516:     }
                   3517:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3518:   for(h=1; h <=nhstepm; h++){
                   3519:     for(d=1; d <=hstepm; d++){
                   3520:       newm=savm;
                   3521:       /* Covariates have to be included here again */
                   3522:       cov[1]=1.;
1.271     brouard  3523:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3524:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3525:         /* Debug */
                   3526:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3527:       cov[2]=agexact;
                   3528:       if(nagesqr==1)
1.222     brouard  3529:        cov[3]= agexact*agexact;
1.266     brouard  3530:       for (k=1; k<=cptcovn;k++){
                   3531:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3532:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3533:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3534:         /* 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)); */
                   3535:       }
1.267     brouard  3536:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3537:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3538:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3539:        /* 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]); */
                   3540:       }
1.319     brouard  3541:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 *//* For product with age */
                   3542:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age error!!!*\/ */
                   3543:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.267     brouard  3544:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  3545:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
1.267     brouard  3546:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3547:        }
                   3548:        /* 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]); */
                   3549:       }
                   3550:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3551:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3552:       }                        
1.217     brouard  3553:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3554:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3555: 
1.218     brouard  3556:       /* Careful transposed matrix */
1.266     brouard  3557:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3558:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3559:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3560:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3561:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3562:       /* if((int)age == 70){ */
                   3563:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3564:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3565:       /*         printf("%d pmmij ",i); */
                   3566:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3567:       /*           printf("%f ",pmmij[i][j]); */
                   3568:       /*         } */
                   3569:       /*         printf(" oldm "); */
                   3570:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3571:       /*           printf("%f ",oldm[i][j]); */
                   3572:       /*         } */
                   3573:       /*         printf("\n"); */
                   3574:       /*       } */
                   3575:       /* } */
                   3576:       savm=oldm;
                   3577:       oldm=newm;
                   3578:     }
                   3579:     for(i=1; i<=nlstate+ndeath; i++)
                   3580:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3581:        po[i][j][h]=newm[i][j];
1.268     brouard  3582:        /* if(h==nhstepm) */
                   3583:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3584:       }
1.268     brouard  3585:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3586:   } /* end h */
1.268     brouard  3587:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3588:   return po;
                   3589: }
                   3590: 
                   3591: 
1.162     brouard  3592: #ifdef NLOPT
                   3593:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3594:   double fret;
                   3595:   double *xt;
                   3596:   int j;
                   3597:   myfunc_data *d2 = (myfunc_data *) pd;
                   3598: /* xt = (p1-1); */
                   3599:   xt=vector(1,n); 
                   3600:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3601: 
                   3602:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3603:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3604:   printf("Function = %.12lf ",fret);
                   3605:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3606:   printf("\n");
                   3607:  free_vector(xt,1,n);
                   3608:   return fret;
                   3609: }
                   3610: #endif
1.126     brouard  3611: 
                   3612: /*************** log-likelihood *************/
                   3613: double func( double *x)
                   3614: {
1.226     brouard  3615:   int i, ii, j, k, mi, d, kk;
                   3616:   int ioffset=0;
                   3617:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3618:   double **out;
                   3619:   double lli; /* Individual log likelihood */
                   3620:   int s1, s2;
1.228     brouard  3621:   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  3622:   double bbh, survp;
                   3623:   long ipmx;
                   3624:   double agexact;
                   3625:   /*extern weight */
                   3626:   /* We are differentiating ll according to initial status */
                   3627:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3628:   /*for(i=1;i<imx;i++) 
                   3629:     printf(" %d\n",s[4][i]);
                   3630:   */
1.162     brouard  3631: 
1.226     brouard  3632:   ++countcallfunc;
1.162     brouard  3633: 
1.226     brouard  3634:   cov[1]=1.;
1.126     brouard  3635: 
1.226     brouard  3636:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3637:   ioffset=0;
1.226     brouard  3638:   if(mle==1){
                   3639:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3640:       /* Computes the values of the ncovmodel covariates of the model
                   3641:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3642:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3643:         to be observed in j being in i according to the model.
                   3644:       */
1.243     brouard  3645:       ioffset=2+nagesqr ;
1.233     brouard  3646:    /* Fixed */
1.319     brouard  3647:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3648:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3649:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3650:        /*  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  3651:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3652:        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)*/
                   3653:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3654:       }
1.226     brouard  3655:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3656:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3657:         has been calculated etc */
                   3658:       /* For an individual i, wav[i] gives the number of effective waves */
                   3659:       /* We compute the contribution to Likelihood of each effective transition
                   3660:         mw[mi][i] is real wave of the mi th effectve wave */
                   3661:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3662:         s2=s[mw[mi+1][i]][i];
                   3663:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3664:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3665:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3666:       */
                   3667:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3668:        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*/
                   3669:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3670:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3671:        }
                   3672:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3673:          for (j=1;j<=nlstate+ndeath;j++){
                   3674:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3675:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3676:          }
                   3677:        for(d=0; d<dh[mi][i]; d++){
                   3678:          newm=savm;
                   3679:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3680:          cov[2]=agexact;
                   3681:          if(nagesqr==1)
                   3682:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3683:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3684:            if(!FixedV[Tvar[Tage[kk]]])
                   3685:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3686:            else
                   3687:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3688:          }
                   3689:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3690:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3691:          savm=oldm;
                   3692:          oldm=newm;
                   3693:        } /* end mult */
                   3694:        
                   3695:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3696:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3697:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3698:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3699:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3700:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3701:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3702:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3703:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3704:                                 * -stepm/2 to stepm/2 .
                   3705:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3706:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3707:                                 */
1.234     brouard  3708:        s1=s[mw[mi][i]][i];
                   3709:        s2=s[mw[mi+1][i]][i];
                   3710:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3711:        /* bias bh is positive if real duration
                   3712:         * is higher than the multiple of stepm and negative otherwise.
                   3713:         */
                   3714:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3715:        if( s2 > nlstate){ 
                   3716:          /* i.e. if s2 is a death state and if the date of death is known 
                   3717:             then the contribution to the likelihood is the probability to 
                   3718:             die between last step unit time and current  step unit time, 
                   3719:             which is also equal to probability to die before dh 
                   3720:             minus probability to die before dh-stepm . 
                   3721:             In version up to 0.92 likelihood was computed
                   3722:             as if date of death was unknown. Death was treated as any other
                   3723:             health state: the date of the interview describes the actual state
                   3724:             and not the date of a change in health state. The former idea was
                   3725:             to consider that at each interview the state was recorded
                   3726:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3727:             introduced the exact date of death then we should have modified
                   3728:             the contribution of an exact death to the likelihood. This new
                   3729:             contribution is smaller and very dependent of the step unit
                   3730:             stepm. It is no more the probability to die between last interview
                   3731:             and month of death but the probability to survive from last
                   3732:             interview up to one month before death multiplied by the
                   3733:             probability to die within a month. Thanks to Chris
                   3734:             Jackson for correcting this bug.  Former versions increased
                   3735:             mortality artificially. The bad side is that we add another loop
                   3736:             which slows down the processing. The difference can be up to 10%
                   3737:             lower mortality.
                   3738:          */
                   3739:          /* If, at the beginning of the maximization mostly, the
                   3740:             cumulative probability or probability to be dead is
                   3741:             constant (ie = 1) over time d, the difference is equal to
                   3742:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3743:             s1 at precedent wave, to be dead a month before current
                   3744:             wave is equal to probability, being at state s1 at
                   3745:             precedent wave, to be dead at mont of the current
                   3746:             wave. Then the observed probability (that this person died)
                   3747:             is null according to current estimated parameter. In fact,
                   3748:             it should be very low but not zero otherwise the log go to
                   3749:             infinity.
                   3750:          */
1.183     brouard  3751: /* #ifdef INFINITYORIGINAL */
                   3752: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3753: /* #else */
                   3754: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3755: /*         lli=log(mytinydouble); */
                   3756: /*       else */
                   3757: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3758: /* #endif */
1.226     brouard  3759:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3760:          
1.226     brouard  3761:        } else if  ( s2==-1 ) { /* alive */
                   3762:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3763:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3764:          /*survp += out[s1][j]; */
                   3765:          lli= log(survp);
                   3766:        }
                   3767:        else if  (s2==-4) { 
                   3768:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3769:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3770:          lli= log(survp); 
                   3771:        } 
                   3772:        else if  (s2==-5) { 
                   3773:          for (j=1,survp=0. ; j<=2; j++)  
                   3774:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3775:          lli= log(survp); 
                   3776:        } 
                   3777:        else{
                   3778:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3779:          /*  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 */
                   3780:        } 
                   3781:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3782:        /*if(lli ==000.0)*/
                   3783:        /*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); */
                   3784:        ipmx +=1;
                   3785:        sw += weight[i];
                   3786:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3787:        /* if (lli < log(mytinydouble)){ */
                   3788:        /*   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); */
                   3789:        /*   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]); */
                   3790:        /* } */
                   3791:       } /* end of wave */
                   3792:     } /* end of individual */
                   3793:   }  else if(mle==2){
                   3794:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  3795:       ioffset=2+nagesqr ;
                   3796:       for (k=1; k<=ncovf;k++)
                   3797:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  3798:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3799:        for(k=1; k <= ncovv ; k++){
                   3800:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3801:        }
1.226     brouard  3802:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3803:          for (j=1;j<=nlstate+ndeath;j++){
                   3804:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3805:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3806:          }
                   3807:        for(d=0; d<=dh[mi][i]; d++){
                   3808:          newm=savm;
                   3809:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3810:          cov[2]=agexact;
                   3811:          if(nagesqr==1)
                   3812:            cov[3]= agexact*agexact;
                   3813:          for (kk=1; kk<=cptcovage;kk++) {
                   3814:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3815:          }
                   3816:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3817:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3818:          savm=oldm;
                   3819:          oldm=newm;
                   3820:        } /* end mult */
                   3821:       
                   3822:        s1=s[mw[mi][i]][i];
                   3823:        s2=s[mw[mi+1][i]][i];
                   3824:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3825:        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 */
                   3826:        ipmx +=1;
                   3827:        sw += weight[i];
                   3828:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3829:       } /* end of wave */
                   3830:     } /* end of individual */
                   3831:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3832:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3833:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3834:       for(mi=1; mi<= wav[i]-1; mi++){
                   3835:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3836:          for (j=1;j<=nlstate+ndeath;j++){
                   3837:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3838:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3839:          }
                   3840:        for(d=0; d<dh[mi][i]; d++){
                   3841:          newm=savm;
                   3842:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3843:          cov[2]=agexact;
                   3844:          if(nagesqr==1)
                   3845:            cov[3]= agexact*agexact;
                   3846:          for (kk=1; kk<=cptcovage;kk++) {
                   3847:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3848:          }
                   3849:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3850:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3851:          savm=oldm;
                   3852:          oldm=newm;
                   3853:        } /* end mult */
                   3854:       
                   3855:        s1=s[mw[mi][i]][i];
                   3856:        s2=s[mw[mi+1][i]][i];
                   3857:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3858:        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 */
                   3859:        ipmx +=1;
                   3860:        sw += weight[i];
                   3861:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3862:       } /* end of wave */
                   3863:     } /* end of individual */
                   3864:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3865:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3866:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3867:       for(mi=1; mi<= wav[i]-1; mi++){
                   3868:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3869:          for (j=1;j<=nlstate+ndeath;j++){
                   3870:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3871:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3872:          }
                   3873:        for(d=0; d<dh[mi][i]; d++){
                   3874:          newm=savm;
                   3875:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3876:          cov[2]=agexact;
                   3877:          if(nagesqr==1)
                   3878:            cov[3]= agexact*agexact;
                   3879:          for (kk=1; kk<=cptcovage;kk++) {
                   3880:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3881:          }
1.126     brouard  3882:        
1.226     brouard  3883:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3884:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3885:          savm=oldm;
                   3886:          oldm=newm;
                   3887:        } /* end mult */
                   3888:       
                   3889:        s1=s[mw[mi][i]][i];
                   3890:        s2=s[mw[mi+1][i]][i];
                   3891:        if( s2 > nlstate){ 
                   3892:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3893:        } else if  ( s2==-1 ) { /* alive */
                   3894:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3895:            survp += out[s1][j];
                   3896:          lli= log(survp);
                   3897:        }else{
                   3898:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3899:        }
                   3900:        ipmx +=1;
                   3901:        sw += weight[i];
                   3902:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3903: /*     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  3904:       } /* end of wave */
                   3905:     } /* end of individual */
                   3906:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3907:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3908:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3909:       for(mi=1; mi<= wav[i]-1; mi++){
                   3910:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3911:          for (j=1;j<=nlstate+ndeath;j++){
                   3912:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3913:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3914:          }
                   3915:        for(d=0; d<dh[mi][i]; d++){
                   3916:          newm=savm;
                   3917:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3918:          cov[2]=agexact;
                   3919:          if(nagesqr==1)
                   3920:            cov[3]= agexact*agexact;
                   3921:          for (kk=1; kk<=cptcovage;kk++) {
                   3922:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3923:          }
1.126     brouard  3924:        
1.226     brouard  3925:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3926:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3927:          savm=oldm;
                   3928:          oldm=newm;
                   3929:        } /* end mult */
                   3930:       
                   3931:        s1=s[mw[mi][i]][i];
                   3932:        s2=s[mw[mi+1][i]][i];
                   3933:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3934:        ipmx +=1;
                   3935:        sw += weight[i];
                   3936:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3937:        /*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]);*/
                   3938:       } /* end of wave */
                   3939:     } /* end of individual */
                   3940:   } /* End of if */
                   3941:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3942:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3943:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3944:   return -l;
1.126     brouard  3945: }
                   3946: 
                   3947: /*************** log-likelihood *************/
                   3948: double funcone( double *x)
                   3949: {
1.228     brouard  3950:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3951:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3952:   int ioffset=0;
1.131     brouard  3953:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3954:   double **out;
                   3955:   double lli; /* Individual log likelihood */
                   3956:   double llt;
                   3957:   int s1, s2;
1.228     brouard  3958:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3959: 
1.126     brouard  3960:   double bbh, survp;
1.187     brouard  3961:   double agexact;
1.214     brouard  3962:   double agebegin, ageend;
1.126     brouard  3963:   /*extern weight */
                   3964:   /* We are differentiating ll according to initial status */
                   3965:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3966:   /*for(i=1;i<imx;i++) 
                   3967:     printf(" %d\n",s[4][i]);
                   3968:   */
                   3969:   cov[1]=1.;
                   3970: 
                   3971:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3972:   ioffset=0;
                   3973:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3974:     /* ioffset=2+nagesqr+cptcovage; */
                   3975:     ioffset=2+nagesqr;
1.232     brouard  3976:     /* Fixed */
1.224     brouard  3977:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3978:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  3979:     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  3980:       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)*/
                   3981: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3982: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3983: /*    cov[2+6]=covar[2][i]; V2  */
                   3984: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3985: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3986: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3987: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3988: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3989: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3990:     }
1.232     brouard  3991:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3992:     /*   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?)*\/ */
                   3993:     /* } */
1.231     brouard  3994:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3995:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3996:     /* } */
1.225     brouard  3997:     
1.233     brouard  3998: 
                   3999:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4000:     /* Wave varying (but not age varying) */
                   4001:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4002:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4003:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4004:       }
1.232     brouard  4005:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4006:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4007:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4008:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4009:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4010:       /* 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  4011:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4012:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4013:       /*       /\* 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]); *\/ */
                   4014:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4015:       /* } */
1.126     brouard  4016:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4017:        for (j=1;j<=nlstate+ndeath;j++){
                   4018:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4019:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4020:        }
1.214     brouard  4021:       
                   4022:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4023:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4024:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4025:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4026:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4027:          and mw[mi+1][i]. dh depends on stepm.*/
                   4028:        newm=savm;
1.247     brouard  4029:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4030:        cov[2]=agexact;
                   4031:        if(nagesqr==1)
                   4032:          cov[3]= agexact*agexact;
                   4033:        for (kk=1; kk<=cptcovage;kk++) {
                   4034:          if(!FixedV[Tvar[Tage[kk]]])
                   4035:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4036:          else
                   4037:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4038:        }
                   4039:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4040:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4041:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4042:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4043:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4044:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4045:        savm=oldm;
                   4046:        oldm=newm;
1.126     brouard  4047:       } /* end mult */
                   4048:       
                   4049:       s1=s[mw[mi][i]][i];
                   4050:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4051:       /* if(s2==-1){ */
1.268     brouard  4052:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4053:       /*       /\* exit(1); *\/ */
                   4054:       /* } */
1.126     brouard  4055:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4056:       /* bias is positive if real duration
                   4057:        * is higher than the multiple of stepm and negative otherwise.
                   4058:        */
                   4059:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4060:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4061:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4062:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4063:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4064:        lli= log(survp);
1.126     brouard  4065:       }else if (mle==1){
1.242     brouard  4066:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4067:       } else if(mle==2){
1.242     brouard  4068:        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  4069:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4070:        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  4071:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4072:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4073:       } else{  /* mle=0 back to 1 */
1.242     brouard  4074:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4075:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4076:       } /* End of if */
                   4077:       ipmx +=1;
                   4078:       sw += weight[i];
                   4079:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  4080:       /*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  4081:       if(globpr){
1.246     brouard  4082:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4083:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4084:                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  4085:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4086:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4087:          llt +=ll[k]*gipmx/gsw;
                   4088:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4089:        }
                   4090:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4091:       }
1.232     brouard  4092:        } /* end of wave */
                   4093: } /* end of individual */
                   4094: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4095: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4096: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4097: if(globpr==0){ /* First time we count the contributions and weights */
                   4098:        gipmx=ipmx;
                   4099:        gsw=sw;
                   4100: }
                   4101: return -l;
1.126     brouard  4102: }
                   4103: 
                   4104: 
                   4105: /*************** function likelione ***********/
1.292     brouard  4106: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4107: {
                   4108:   /* This routine should help understanding what is done with 
                   4109:      the selection of individuals/waves and
                   4110:      to check the exact contribution to the likelihood.
                   4111:      Plotting could be done.
                   4112:    */
                   4113:   int k;
                   4114: 
                   4115:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4116:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4117:     strcat(fileresilk,fileresu);
1.126     brouard  4118:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4119:       printf("Problem with resultfile: %s\n", fileresilk);
                   4120:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4121:     }
1.214     brouard  4122:     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");
                   4123:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4124:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4125:     for(k=1; k<=nlstate; k++) 
                   4126:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4127:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4128:   }
                   4129: 
1.292     brouard  4130:   *fretone=(*func)(p);
1.126     brouard  4131:   if(*globpri !=0){
                   4132:     fclose(ficresilk);
1.205     brouard  4133:     if (mle ==0)
                   4134:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4135:     else if(mle >=1)
                   4136:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4137:     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  4138:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4139:       
                   4140:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4141:       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  4142: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4143:     }
1.207     brouard  4144:     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  4145: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4146:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4147: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4148:     fflush(fichtm);
1.205     brouard  4149:   }
1.126     brouard  4150:   return;
                   4151: }
                   4152: 
                   4153: 
                   4154: /*********** Maximum Likelihood Estimation ***************/
                   4155: 
                   4156: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4157: {
1.319     brouard  4158:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4159:   double **xi;
                   4160:   double fret;
                   4161:   double fretone; /* Only one call to likelihood */
                   4162:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4163: 
                   4164: #ifdef NLOPT
                   4165:   int creturn;
                   4166:   nlopt_opt opt;
                   4167:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4168:   double *lb;
                   4169:   double minf; /* the minimum objective value, upon return */
                   4170:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4171:   myfunc_data dinst, *d = &dinst;
                   4172: #endif
                   4173: 
                   4174: 
1.126     brouard  4175:   xi=matrix(1,npar,1,npar);
                   4176:   for (i=1;i<=npar;i++)
                   4177:     for (j=1;j<=npar;j++)
                   4178:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4179:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4180:   strcpy(filerespow,"POW_"); 
1.126     brouard  4181:   strcat(filerespow,fileres);
                   4182:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4183:     printf("Problem with resultfile: %s\n", filerespow);
                   4184:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4185:   }
                   4186:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4187:   for (i=1;i<=nlstate;i++)
                   4188:     for(j=1;j<=nlstate+ndeath;j++)
                   4189:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4190:   fprintf(ficrespow,"\n");
1.162     brouard  4191: #ifdef POWELL
1.319     brouard  4192: #ifdef LINMINORIGINAL
                   4193: #else /* LINMINORIGINAL */
                   4194:   
                   4195:   flatdir=ivector(1,npar); 
                   4196:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4197: #endif /*LINMINORIGINAL */
                   4198: 
                   4199: #ifdef FLATSUP
                   4200:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4201:   /* reorganizing p by suppressing flat directions */
                   4202:   for(i=1, jk=1; i <=nlstate; i++){
                   4203:     for(k=1; k <=(nlstate+ndeath); k++){
                   4204:       if (k != i) {
                   4205:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4206:         if(flatdir[jk]==1){
                   4207:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4208:         }
                   4209:         for(j=1; j <=ncovmodel; j++){
                   4210:           printf("%12.7f ",p[jk]);
                   4211:           jk++; 
                   4212:         }
                   4213:         printf("\n");
                   4214:       }
                   4215:     }
                   4216:   }
                   4217: /* skipping */
                   4218:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4219:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4220:     for(k=1; k <=(nlstate+ndeath); k++){
                   4221:       if (k != i) {
                   4222:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4223:         if(flatdir[jk]==1){
                   4224:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4225:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4226:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4227:             /*q[jjk]=p[jk];*/
                   4228:           }
                   4229:         }else{
                   4230:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4231:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4232:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4233:             /*q[jjk]=p[jk];*/
                   4234:           }
                   4235:         }
                   4236:         printf("\n");
                   4237:       }
                   4238:       fflush(stdout);
                   4239:     }
                   4240:   }
                   4241:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4242: #else  /* FLATSUP */
1.126     brouard  4243:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4244: #endif  /* FLATSUP */
                   4245: 
                   4246: #ifdef LINMINORIGINAL
                   4247: #else
                   4248:       free_ivector(flatdir,1,npar); 
                   4249: #endif  /* LINMINORIGINAL*/
                   4250: #endif /* POWELL */
1.126     brouard  4251: 
1.162     brouard  4252: #ifdef NLOPT
                   4253: #ifdef NEWUOA
                   4254:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4255: #else
                   4256:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4257: #endif
                   4258:   lb=vector(0,npar-1);
                   4259:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4260:   nlopt_set_lower_bounds(opt, lb);
                   4261:   nlopt_set_initial_step1(opt, 0.1);
                   4262:   
                   4263:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4264:   d->function = func;
                   4265:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4266:   nlopt_set_min_objective(opt, myfunc, d);
                   4267:   nlopt_set_xtol_rel(opt, ftol);
                   4268:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4269:     printf("nlopt failed! %d\n",creturn); 
                   4270:   }
                   4271:   else {
                   4272:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4273:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4274:     iter=1; /* not equal */
                   4275:   }
                   4276:   nlopt_destroy(opt);
                   4277: #endif
1.319     brouard  4278: #ifdef FLATSUP
                   4279:   /* npared = npar -flatd/ncovmodel; */
                   4280:   /* xired= matrix(1,npared,1,npared); */
                   4281:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4282:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4283:   /* free_matrix(xire,1,npared,1,npared); */
                   4284: #else  /* FLATSUP */
                   4285: #endif /* FLATSUP */
1.126     brouard  4286:   free_matrix(xi,1,npar,1,npar);
                   4287:   fclose(ficrespow);
1.203     brouard  4288:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4289:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4290:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4291: 
                   4292: }
                   4293: 
                   4294: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4295: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4296: {
                   4297:   double  **a,**y,*x,pd;
1.203     brouard  4298:   /* double **hess; */
1.164     brouard  4299:   int i, j;
1.126     brouard  4300:   int *indx;
                   4301: 
                   4302:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4303:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4304:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4305:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4306:   double gompertz(double p[]);
1.203     brouard  4307:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4308: 
                   4309:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4310:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4311:   for (i=1;i<=npar;i++){
1.203     brouard  4312:     printf("%d-",i);fflush(stdout);
                   4313:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4314:    
                   4315:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4316:     
                   4317:     /*  printf(" %f ",p[i]);
                   4318:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4319:   }
                   4320:   
                   4321:   for (i=1;i<=npar;i++) {
                   4322:     for (j=1;j<=npar;j++)  {
                   4323:       if (j>i) { 
1.203     brouard  4324:        printf(".%d-%d",i,j);fflush(stdout);
                   4325:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4326:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4327:        
                   4328:        hess[j][i]=hess[i][j];    
                   4329:        /*printf(" %lf ",hess[i][j]);*/
                   4330:       }
                   4331:     }
                   4332:   }
                   4333:   printf("\n");
                   4334:   fprintf(ficlog,"\n");
                   4335: 
                   4336:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4337:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4338:   
                   4339:   a=matrix(1,npar,1,npar);
                   4340:   y=matrix(1,npar,1,npar);
                   4341:   x=vector(1,npar);
                   4342:   indx=ivector(1,npar);
                   4343:   for (i=1;i<=npar;i++)
                   4344:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4345:   ludcmp(a,npar,indx,&pd);
                   4346: 
                   4347:   for (j=1;j<=npar;j++) {
                   4348:     for (i=1;i<=npar;i++) x[i]=0;
                   4349:     x[j]=1;
                   4350:     lubksb(a,npar,indx,x);
                   4351:     for (i=1;i<=npar;i++){ 
                   4352:       matcov[i][j]=x[i];
                   4353:     }
                   4354:   }
                   4355: 
                   4356:   printf("\n#Hessian matrix#\n");
                   4357:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4358:   for (i=1;i<=npar;i++) { 
                   4359:     for (j=1;j<=npar;j++) { 
1.203     brouard  4360:       printf("%.6e ",hess[i][j]);
                   4361:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4362:     }
                   4363:     printf("\n");
                   4364:     fprintf(ficlog,"\n");
                   4365:   }
                   4366: 
1.203     brouard  4367:   /* printf("\n#Covariance matrix#\n"); */
                   4368:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4369:   /* for (i=1;i<=npar;i++) {  */
                   4370:   /*   for (j=1;j<=npar;j++) {  */
                   4371:   /*     printf("%.6e ",matcov[i][j]); */
                   4372:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4373:   /*   } */
                   4374:   /*   printf("\n"); */
                   4375:   /*   fprintf(ficlog,"\n"); */
                   4376:   /* } */
                   4377: 
1.126     brouard  4378:   /* Recompute Inverse */
1.203     brouard  4379:   /* for (i=1;i<=npar;i++) */
                   4380:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4381:   /* ludcmp(a,npar,indx,&pd); */
                   4382: 
                   4383:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4384: 
                   4385:   /* for (j=1;j<=npar;j++) { */
                   4386:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4387:   /*   x[j]=1; */
                   4388:   /*   lubksb(a,npar,indx,x); */
                   4389:   /*   for (i=1;i<=npar;i++){  */
                   4390:   /*     y[i][j]=x[i]; */
                   4391:   /*     printf("%.3e ",y[i][j]); */
                   4392:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4393:   /*   } */
                   4394:   /*   printf("\n"); */
                   4395:   /*   fprintf(ficlog,"\n"); */
                   4396:   /* } */
                   4397: 
                   4398:   /* Verifying the inverse matrix */
                   4399: #ifdef DEBUGHESS
                   4400:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4401: 
1.203     brouard  4402:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4403:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4404: 
                   4405:   for (j=1;j<=npar;j++) {
                   4406:     for (i=1;i<=npar;i++){ 
1.203     brouard  4407:       printf("%.2f ",y[i][j]);
                   4408:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4409:     }
                   4410:     printf("\n");
                   4411:     fprintf(ficlog,"\n");
                   4412:   }
1.203     brouard  4413: #endif
1.126     brouard  4414: 
                   4415:   free_matrix(a,1,npar,1,npar);
                   4416:   free_matrix(y,1,npar,1,npar);
                   4417:   free_vector(x,1,npar);
                   4418:   free_ivector(indx,1,npar);
1.203     brouard  4419:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4420: 
                   4421: 
                   4422: }
                   4423: 
                   4424: /*************** hessian matrix ****************/
                   4425: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4426: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4427:   int i;
                   4428:   int l=1, lmax=20;
1.203     brouard  4429:   double k1,k2, res, fx;
1.132     brouard  4430:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4431:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4432:   int k=0,kmax=10;
                   4433:   double l1;
                   4434: 
                   4435:   fx=func(x);
                   4436:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4437:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4438:     l1=pow(10,l);
                   4439:     delts=delt;
                   4440:     for(k=1 ; k <kmax; k=k+1){
                   4441:       delt = delta*(l1*k);
                   4442:       p2[theta]=x[theta] +delt;
1.145     brouard  4443:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4444:       p2[theta]=x[theta]-delt;
                   4445:       k2=func(p2)-fx;
                   4446:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4447:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4448:       
1.203     brouard  4449: #ifdef DEBUGHESSII
1.126     brouard  4450:       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);
                   4451:       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);
                   4452: #endif
                   4453:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4454:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4455:        k=kmax;
                   4456:       }
                   4457:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4458:        k=kmax; l=lmax*10;
1.126     brouard  4459:       }
                   4460:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4461:        delts=delt;
                   4462:       }
1.203     brouard  4463:     } /* End loop k */
1.126     brouard  4464:   }
                   4465:   delti[theta]=delts;
                   4466:   return res; 
                   4467:   
                   4468: }
                   4469: 
1.203     brouard  4470: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4471: {
                   4472:   int i;
1.164     brouard  4473:   int l=1, lmax=20;
1.126     brouard  4474:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4475:   double p2[MAXPARM+1];
1.203     brouard  4476:   int k, kmax=1;
                   4477:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4478: 
                   4479:   int firstime=0;
1.203     brouard  4480:   
1.126     brouard  4481:   fx=func(x);
1.203     brouard  4482:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4483:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4484:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4485:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4486:     k1=func(p2)-fx;
                   4487:   
1.203     brouard  4488:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4489:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4490:     k2=func(p2)-fx;
                   4491:   
1.203     brouard  4492:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4493:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4494:     k3=func(p2)-fx;
                   4495:   
1.203     brouard  4496:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4497:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4498:     k4=func(p2)-fx;
1.203     brouard  4499:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4500:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4501:       firstime=1;
1.203     brouard  4502:       kmax=kmax+10;
1.208     brouard  4503:     }
                   4504:     if(kmax >=10 || firstime ==1){
1.246     brouard  4505:       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);
                   4506:       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  4507:       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);
                   4508:       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);
                   4509:     }
                   4510: #ifdef DEBUGHESSIJ
                   4511:     v1=hess[thetai][thetai];
                   4512:     v2=hess[thetaj][thetaj];
                   4513:     cv12=res;
                   4514:     /* Computing eigen value of Hessian matrix */
                   4515:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4516:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4517:     if ((lc2 <0) || (lc1 <0) ){
                   4518:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4519:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4520:       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);
                   4521:       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);
                   4522:     }
1.126     brouard  4523: #endif
                   4524:   }
                   4525:   return res;
                   4526: }
                   4527: 
1.203     brouard  4528:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4529: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4530: /* { */
                   4531: /*   int i; */
                   4532: /*   int l=1, lmax=20; */
                   4533: /*   double k1,k2,k3,k4,res,fx; */
                   4534: /*   double p2[MAXPARM+1]; */
                   4535: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4536: /*   int k=0,kmax=10; */
                   4537: /*   double l1; */
                   4538:   
                   4539: /*   fx=func(x); */
                   4540: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4541: /*     l1=pow(10,l); */
                   4542: /*     delts=delt; */
                   4543: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4544: /*       delt = delti*(l1*k); */
                   4545: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4546: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4547: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4548: /*       k1=func(p2)-fx; */
                   4549:       
                   4550: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4551: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4552: /*       k2=func(p2)-fx; */
                   4553:       
                   4554: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4555: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4556: /*       k3=func(p2)-fx; */
                   4557:       
                   4558: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4559: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4560: /*       k4=func(p2)-fx; */
                   4561: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4562: /* #ifdef DEBUGHESSIJ */
                   4563: /*       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); */
                   4564: /*       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); */
                   4565: /* #endif */
                   4566: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4567: /*     k=kmax; */
                   4568: /*       } */
                   4569: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4570: /*     k=kmax; l=lmax*10; */
                   4571: /*       } */
                   4572: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4573: /*     delts=delt; */
                   4574: /*       } */
                   4575: /*     } /\* End loop k *\/ */
                   4576: /*   } */
                   4577: /*   delti[theta]=delts; */
                   4578: /*   return res;  */
                   4579: /* } */
                   4580: 
                   4581: 
1.126     brouard  4582: /************** Inverse of matrix **************/
                   4583: void ludcmp(double **a, int n, int *indx, double *d) 
                   4584: { 
                   4585:   int i,imax,j,k; 
                   4586:   double big,dum,sum,temp; 
                   4587:   double *vv; 
                   4588:  
                   4589:   vv=vector(1,n); 
                   4590:   *d=1.0; 
                   4591:   for (i=1;i<=n;i++) { 
                   4592:     big=0.0; 
                   4593:     for (j=1;j<=n;j++) 
                   4594:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4595:     if (big == 0.0){
                   4596:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4597:       for (j=1;j<=n;j++) {
                   4598:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4599:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4600:       }
                   4601:       fflush(ficlog);
                   4602:       fclose(ficlog);
                   4603:       nrerror("Singular matrix in routine ludcmp"); 
                   4604:     }
1.126     brouard  4605:     vv[i]=1.0/big; 
                   4606:   } 
                   4607:   for (j=1;j<=n;j++) { 
                   4608:     for (i=1;i<j;i++) { 
                   4609:       sum=a[i][j]; 
                   4610:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4611:       a[i][j]=sum; 
                   4612:     } 
                   4613:     big=0.0; 
                   4614:     for (i=j;i<=n;i++) { 
                   4615:       sum=a[i][j]; 
                   4616:       for (k=1;k<j;k++) 
                   4617:        sum -= a[i][k]*a[k][j]; 
                   4618:       a[i][j]=sum; 
                   4619:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4620:        big=dum; 
                   4621:        imax=i; 
                   4622:       } 
                   4623:     } 
                   4624:     if (j != imax) { 
                   4625:       for (k=1;k<=n;k++) { 
                   4626:        dum=a[imax][k]; 
                   4627:        a[imax][k]=a[j][k]; 
                   4628:        a[j][k]=dum; 
                   4629:       } 
                   4630:       *d = -(*d); 
                   4631:       vv[imax]=vv[j]; 
                   4632:     } 
                   4633:     indx[j]=imax; 
                   4634:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4635:     if (j != n) { 
                   4636:       dum=1.0/(a[j][j]); 
                   4637:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4638:     } 
                   4639:   } 
                   4640:   free_vector(vv,1,n);  /* Doesn't work */
                   4641: ;
                   4642: } 
                   4643: 
                   4644: void lubksb(double **a, int n, int *indx, double b[]) 
                   4645: { 
                   4646:   int i,ii=0,ip,j; 
                   4647:   double sum; 
                   4648:  
                   4649:   for (i=1;i<=n;i++) { 
                   4650:     ip=indx[i]; 
                   4651:     sum=b[ip]; 
                   4652:     b[ip]=b[i]; 
                   4653:     if (ii) 
                   4654:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4655:     else if (sum) ii=i; 
                   4656:     b[i]=sum; 
                   4657:   } 
                   4658:   for (i=n;i>=1;i--) { 
                   4659:     sum=b[i]; 
                   4660:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4661:     b[i]=sum/a[i][i]; 
                   4662:   } 
                   4663: } 
                   4664: 
                   4665: void pstamp(FILE *fichier)
                   4666: {
1.196     brouard  4667:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4668: }
                   4669: 
1.297     brouard  4670: void date2dmy(double date,double *day, double *month, double *year){
                   4671:   double yp=0., yp1=0., yp2=0.;
                   4672:   
                   4673:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4674:                        fractional in yp1 */
                   4675:   *year=yp;
                   4676:   yp2=modf((yp1*12),&yp);
                   4677:   *month=yp;
                   4678:   yp1=modf((yp2*30.5),&yp);
                   4679:   *day=yp;
                   4680:   if(*day==0) *day=1;
                   4681:   if(*month==0) *month=1;
                   4682: }
                   4683: 
1.253     brouard  4684: 
                   4685: 
1.126     brouard  4686: /************ Frequencies ********************/
1.251     brouard  4687: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4688:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4689:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4690: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4691:   
1.265     brouard  4692:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4693:   int iind=0, iage=0;
                   4694:   int mi; /* Effective wave */
                   4695:   int first;
                   4696:   double ***freq; /* Frequencies */
1.268     brouard  4697:   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 */
                   4698:   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  4699:   double *meanq, *stdq, *idq;
1.226     brouard  4700:   double **meanqt;
                   4701:   double *pp, **prop, *posprop, *pospropt;
                   4702:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4703:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4704:   double agebegin, ageend;
                   4705:     
                   4706:   pp=vector(1,nlstate);
1.251     brouard  4707:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4708:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4709:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4710:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4711:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4712:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4713:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4714:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4715:   strcpy(fileresp,"P_");
                   4716:   strcat(fileresp,fileresu);
                   4717:   /*strcat(fileresphtm,fileresu);*/
                   4718:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4719:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4720:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4721:     exit(0);
                   4722:   }
1.240     brouard  4723:   
1.226     brouard  4724:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4725:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4726:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4727:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4728:     fflush(ficlog);
                   4729:     exit(70); 
                   4730:   }
                   4731:   else{
                   4732:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4733: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4734: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4735:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4736:   }
1.319     brouard  4737:   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  4738:   
1.226     brouard  4739:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4740:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4741:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4742:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4743:     fflush(ficlog);
                   4744:     exit(70); 
1.240     brouard  4745:   } else{
1.226     brouard  4746:     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  4747: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4748: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4749:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4750:   }
1.319     brouard  4751:   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  4752:   
1.253     brouard  4753:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4754:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4755:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4756:   j1=0;
1.126     brouard  4757:   
1.227     brouard  4758:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4759:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4760:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4761:   
                   4762:   
1.226     brouard  4763:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4764:      reference=low_education V1=0,V2=0
                   4765:      med_educ                V1=1 V2=0, 
                   4766:      high_educ               V1=0 V2=1
                   4767:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4768:   */
1.249     brouard  4769:   dateintsum=0;
                   4770:   k2cpt=0;
                   4771: 
1.253     brouard  4772:   if(cptcoveff == 0 )
1.265     brouard  4773:     nl=1;  /* Constant and age model only */
1.253     brouard  4774:   else
                   4775:     nl=2;
1.265     brouard  4776: 
                   4777:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4778:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4779:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4780:    *     freq[s1][s2][iage] =0.
                   4781:    *     Loop on iind
                   4782:    *       ++freq[s1][s2][iage] weighted
                   4783:    *     end iind
                   4784:    *     if covariate and j!0
                   4785:    *       headers Variable on one line
                   4786:    *     endif cov j!=0
                   4787:    *     header of frequency table by age
                   4788:    *     Loop on age
                   4789:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4790:    *       pos+=freq[s1][s2][iage] weighted
                   4791:    *       Loop on s1 initial state
                   4792:    *         fprintf(ficresp
                   4793:    *       end s1
                   4794:    *     end age
                   4795:    *     if j!=0 computes starting values
                   4796:    *     end compute starting values
                   4797:    *   end j1
                   4798:    * end nl 
                   4799:    */
1.253     brouard  4800:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4801:     if(nj==1)
                   4802:       j=0;  /* First pass for the constant */
1.265     brouard  4803:     else{
1.253     brouard  4804:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4805:     }
1.251     brouard  4806:     first=1;
1.265     brouard  4807:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all covariates combination of the model, excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
1.251     brouard  4808:       posproptt=0.;
                   4809:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4810:        scanf("%d", i);*/
                   4811:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4812:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4813:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4814:            freq[i][s2][m]=0;
1.251     brouard  4815:       
                   4816:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4817:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4818:          prop[i][m]=0;
                   4819:        posprop[i]=0;
                   4820:        pospropt[i]=0;
                   4821:       }
1.283     brouard  4822:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4823:         idq[z1]=0.;
                   4824:         meanq[z1]=0.;
                   4825:         stdq[z1]=0.;
1.283     brouard  4826:       }
                   4827:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4828:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4829:       /*         meanqt[m][z1]=0.; */
                   4830:       /*       } */
                   4831:       /* }       */
1.251     brouard  4832:       /* dateintsum=0; */
                   4833:       /* k2cpt=0; */
                   4834:       
1.265     brouard  4835:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4836:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4837:        bool=1;
                   4838:        if(j !=0){
                   4839:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4840:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4841:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4842:                /* if(Tvaraff[z1] ==-20){ */
                   4843:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4844:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4845:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4846:                /* }else  */
                   4847:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4848:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4849:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4850:                  /* 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", 
                   4851:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4852:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4853:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4854:                } /* Onlyf fixed */
                   4855:              } /* end z1 */
                   4856:            } /* cptcovn > 0 */
                   4857:          } /* end any */
                   4858:        }/* end j==0 */
1.265     brouard  4859:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4860:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4861:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4862:            m=mw[mi][iind];
                   4863:            if(j!=0){
                   4864:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4865:                for (z1=1; z1<=cptcoveff; z1++) {
                   4866:                  if( Fixed[Tmodelind[z1]]==1){
                   4867:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4868:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4869:                                                                                      value is -1, we don't select. It differs from the 
                   4870:                                                                                      constant and age model which counts them. */
                   4871:                      bool=0; /* not selected */
                   4872:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4873:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4874:                      bool=0;
                   4875:                    }
                   4876:                  }
                   4877:                }
                   4878:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4879:            } /* end j==0 */
                   4880:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4881:            if(bool==1){ /*Selected */
1.251     brouard  4882:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4883:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4884:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4885:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4886:              if(m >=firstpass && m <=lastpass){
                   4887:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4888:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4889:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4890:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4891:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4892:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4893:                if (m<lastpass) {
                   4894:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4895:                  /*   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]); */
                   4896:                  if(s[m][iind]==-1)
                   4897:                    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.));
                   4898:                  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  4899:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   4900:                    if(!isnan(covar[ncovcol+z1][iind])){
                   4901:                        idq[z1]=idq[z1]+weight[iind];
                   4902:                        meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4903:                        /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   4904:                        stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4905:                    }
1.284     brouard  4906:                  }
1.251     brouard  4907:                  /* if((int)agev[m][iind] == 55) */
                   4908:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4909:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4910:                  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  4911:                }
1.251     brouard  4912:              } /* end if between passes */  
                   4913:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4914:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4915:                k2cpt++;
                   4916:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4917:              }
1.251     brouard  4918:            }else{
                   4919:              bool=1;
                   4920:            }/* end bool 2 */
                   4921:          } /* end m */
1.284     brouard  4922:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4923:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4924:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4925:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4926:          /* } */
1.251     brouard  4927:        } /* end bool */
                   4928:       } /* end iind = 1 to imx */
1.319     brouard  4929:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  4930:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4931:       
                   4932:       
                   4933:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4934:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4935:         pstamp(ficresp);
1.251     brouard  4936:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4937:         pstamp(ficresp);
1.251     brouard  4938:        printf( "\n#********** Variable "); 
                   4939:        fprintf(ficresp, "\n#********** Variable "); 
                   4940:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4941:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4942:        fprintf(ficlog, "\n#********** Variable "); 
                   4943:        for (z1=1; z1<=cptcoveff; z1++){
                   4944:          if(!FixedV[Tvaraff[z1]]){
                   4945:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4946:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4947:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4948:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4949:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4950:          }else{
1.251     brouard  4951:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4952:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4953:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4954:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4955:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4956:          }
                   4957:        }
                   4958:        printf( "**********\n#");
                   4959:        fprintf(ficresp, "**********\n#");
                   4960:        fprintf(ficresphtm, "**********</h3>\n");
                   4961:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4962:        fprintf(ficlog, "**********\n");
                   4963:       }
1.284     brouard  4964:       /*
                   4965:        Printing means of quantitative variables if any
                   4966:       */
                   4967:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  4968:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  4969:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  4970:        if(weightopt==1){
                   4971:          printf(" Weighted mean and standard deviation of");
                   4972:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4973:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4974:        }
1.311     brouard  4975:        /* mu = \frac{w x}{\sum w}
                   4976:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   4977:        */
                   4978:        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]));
                   4979:        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]));
                   4980:        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  4981:       }
                   4982:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4983:       /*       for(m=1;m<=lastpass;m++){ */
                   4984:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4985:       /*   } */
                   4986:       /* } */
1.283     brouard  4987: 
1.251     brouard  4988:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4989:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4990:         fprintf(ficresp, " Age");
                   4991:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.251     brouard  4992:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4993:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4994:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4995:       }
1.265     brouard  4996:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4997:       fprintf(ficresphtm, "\n");
                   4998:       
                   4999:       /* Header of frequency table by age */
                   5000:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5001:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5002:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5003:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5004:          if(s2!=0 && m!=0)
                   5005:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5006:        }
1.226     brouard  5007:       }
1.251     brouard  5008:       fprintf(ficresphtmfr, "\n");
                   5009:     
                   5010:       /* For each age */
                   5011:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5012:        fprintf(ficresphtm,"<tr>");
                   5013:        if(iage==iagemax+1){
                   5014:          fprintf(ficlog,"1");
                   5015:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5016:        }else if(iage==iagemax+2){
                   5017:          fprintf(ficlog,"0");
                   5018:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5019:        }else if(iage==iagemax+3){
                   5020:          fprintf(ficlog,"Total");
                   5021:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5022:        }else{
1.240     brouard  5023:          if(first==1){
1.251     brouard  5024:            first=0;
                   5025:            printf("See log file for details...\n");
                   5026:          }
                   5027:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5028:          fprintf(ficlog,"Age %d", iage);
                   5029:        }
1.265     brouard  5030:        for(s1=1; s1 <=nlstate ; s1++){
                   5031:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5032:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5033:        }
1.265     brouard  5034:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5035:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5036:            pos += freq[s1][m][iage];
                   5037:          if(pp[s1]>=1.e-10){
1.251     brouard  5038:            if(first==1){
1.265     brouard  5039:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5040:            }
1.265     brouard  5041:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5042:          }else{
                   5043:            if(first==1)
1.265     brouard  5044:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5045:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5046:          }
                   5047:        }
                   5048:       
1.265     brouard  5049:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5050:          /* posprop[s1]=0; */
                   5051:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5052:            pp[s1] += freq[s1][m][iage];
                   5053:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5054:       
                   5055:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5056:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5057:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5058:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5059:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5060:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5061:        }
                   5062:        
                   5063:        /* Writing ficresp */
                   5064:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   5065:           if( iage <= iagemax){
                   5066:            fprintf(ficresp," %d",iage);
                   5067:           }
                   5068:         }else if( nj==2){
                   5069:           if( iage <= iagemax){
                   5070:            fprintf(ficresp," %d",iage);
                   5071:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5072:           }
1.240     brouard  5073:        }
1.265     brouard  5074:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5075:          if(pos>=1.e-5){
1.251     brouard  5076:            if(first==1)
1.265     brouard  5077:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5078:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5079:          }else{
                   5080:            if(first==1)
1.265     brouard  5081:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5082:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5083:          }
                   5084:          if( iage <= iagemax){
                   5085:            if(pos>=1.e-5){
1.265     brouard  5086:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   5087:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5088:               }else if( nj==2){
                   5089:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5090:               }
                   5091:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5092:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5093:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5094:            } else{
                   5095:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   5096:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5097:            }
1.240     brouard  5098:          }
1.265     brouard  5099:          pospropt[s1] +=posprop[s1];
                   5100:        } /* end loop s1 */
1.251     brouard  5101:        /* pospropt=0.; */
1.265     brouard  5102:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5103:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5104:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5105:              if(first==1){
1.265     brouard  5106:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5107:              }
1.265     brouard  5108:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5109:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5110:            }
1.265     brouard  5111:            if(s1!=0 && m!=0)
                   5112:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5113:          }
1.265     brouard  5114:        } /* end loop s1 */
1.251     brouard  5115:        posproptt=0.; 
1.265     brouard  5116:        for(s1=1; s1 <=nlstate; s1++){
                   5117:          posproptt += pospropt[s1];
1.251     brouard  5118:        }
                   5119:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5120:        fprintf(ficresphtm,"</tr>\n");
                   5121:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   5122:          if(iage <= iagemax)
                   5123:            fprintf(ficresp,"\n");
1.240     brouard  5124:        }
1.251     brouard  5125:        if(first==1)
                   5126:          printf("Others in log...\n");
                   5127:        fprintf(ficlog,"\n");
                   5128:       } /* end loop age iage */
1.265     brouard  5129:       
1.251     brouard  5130:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5131:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5132:        if(posproptt < 1.e-5){
1.265     brouard  5133:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5134:        }else{
1.265     brouard  5135:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5136:        }
1.226     brouard  5137:       }
1.251     brouard  5138:       fprintf(ficresphtm,"</tr>\n");
                   5139:       fprintf(ficresphtm,"</table>\n");
                   5140:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5141:       if(posproptt < 1.e-5){
1.251     brouard  5142:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5143:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5144:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5145:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5146:        invalidvarcomb[j1]=1;
1.226     brouard  5147:       }else{
1.251     brouard  5148:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5149:        invalidvarcomb[j1]=0;
1.226     brouard  5150:       }
1.251     brouard  5151:       fprintf(ficresphtmfr,"</table>\n");
                   5152:       fprintf(ficlog,"\n");
                   5153:       if(j!=0){
                   5154:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5155:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5156:          for(k=1; k <=(nlstate+ndeath); k++){
                   5157:            if (k != i) {
1.265     brouard  5158:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5159:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5160:                  if(j1==1){ /* All dummy covariates to zero */
                   5161:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5162:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5163:                    printf("%d%d ",i,k);
                   5164:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5165:                    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]));
                   5166:                    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]));
                   5167:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5168:                  }
1.253     brouard  5169:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5170:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5171:                    x[iage]= (double)iage;
                   5172:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5173:                    /* 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  5174:                  }
1.268     brouard  5175:                  /* Some are not finite, but linreg will ignore these ages */
                   5176:                  no=0;
1.253     brouard  5177:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5178:                  pstart[s1]=b;
                   5179:                  pstart[s1-1]=a;
1.252     brouard  5180:                }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 */ 
                   5181:                  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]);
                   5182:                  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  5183:                  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  5184:                  printf("%d%d ",i,k);
                   5185:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5186:                  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  5187:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5188:                  ;
                   5189:                }
                   5190:                /* printf("%12.7f )", param[i][jj][k]); */
                   5191:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5192:                s1++; 
1.251     brouard  5193:              } /* end jj */
                   5194:            } /* end k!= i */
                   5195:          } /* end k */
1.265     brouard  5196:        } /* end i, s1 */
1.251     brouard  5197:       } /* end j !=0 */
                   5198:     } /* end selected combination of covariate j1 */
                   5199:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5200:       printf("#Freqsummary: Starting values for the constants:\n");
                   5201:       fprintf(ficlog,"\n");
1.265     brouard  5202:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5203:        for(k=1; k <=(nlstate+ndeath); k++){
                   5204:          if (k != i) {
                   5205:            printf("%d%d ",i,k);
                   5206:            fprintf(ficlog,"%d%d ",i,k);
                   5207:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5208:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5209:              if(jj==1){ /* Age has to be done */
1.265     brouard  5210:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5211:                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]));
                   5212:                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  5213:              }
                   5214:              /* printf("%12.7f )", param[i][jj][k]); */
                   5215:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5216:              s1++; 
1.250     brouard  5217:            }
1.251     brouard  5218:            printf("\n");
                   5219:            fprintf(ficlog,"\n");
1.250     brouard  5220:          }
                   5221:        }
1.284     brouard  5222:       } /* end of state i */
1.251     brouard  5223:       printf("#Freqsummary\n");
                   5224:       fprintf(ficlog,"\n");
1.265     brouard  5225:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5226:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5227:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5228:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5229:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5230:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5231:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5232:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5233:          /* } */
                   5234:        }
1.265     brouard  5235:       } /* end loop s1 */
1.251     brouard  5236:       
                   5237:       printf("\n");
                   5238:       fprintf(ficlog,"\n");
                   5239:     } /* end j=0 */
1.249     brouard  5240:   } /* end j */
1.252     brouard  5241: 
1.253     brouard  5242:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5243:     for(i=1, jk=1; i <=nlstate; i++){
                   5244:       for(j=1; j <=nlstate+ndeath; j++){
                   5245:        if(j!=i){
                   5246:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5247:          printf("%1d%1d",i,j);
                   5248:          fprintf(ficparo,"%1d%1d",i,j);
                   5249:          for(k=1; k<=ncovmodel;k++){
                   5250:            /*    printf(" %lf",param[i][j][k]); */
                   5251:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5252:            p[jk]=pstart[jk];
                   5253:            printf(" %f ",pstart[jk]);
                   5254:            fprintf(ficparo," %f ",pstart[jk]);
                   5255:            jk++;
                   5256:          }
                   5257:          printf("\n");
                   5258:          fprintf(ficparo,"\n");
                   5259:        }
                   5260:       }
                   5261:     }
                   5262:   } /* end mle=-2 */
1.226     brouard  5263:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5264:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5265:   
1.226     brouard  5266:   fclose(ficresp);
                   5267:   fclose(ficresphtm);
                   5268:   fclose(ficresphtmfr);
1.283     brouard  5269:   free_vector(idq,1,nqfveff);
1.226     brouard  5270:   free_vector(meanq,1,nqfveff);
1.284     brouard  5271:   free_vector(stdq,1,nqfveff);
1.226     brouard  5272:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5273:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5274:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5275:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5276:   free_vector(pospropt,1,nlstate);
                   5277:   free_vector(posprop,1,nlstate);
1.251     brouard  5278:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5279:   free_vector(pp,1,nlstate);
                   5280:   /* End of freqsummary */
                   5281: }
1.126     brouard  5282: 
1.268     brouard  5283: /* Simple linear regression */
                   5284: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5285: 
                   5286:   /* y=a+bx regression */
                   5287:   double   sumx = 0.0;                        /* sum of x                      */
                   5288:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5289:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5290:   double   sumy = 0.0;                        /* sum of y                      */
                   5291:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5292:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5293:   double yhat;
                   5294:   
                   5295:   double denom=0;
                   5296:   int i;
                   5297:   int ne=*no;
                   5298:   
                   5299:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5300:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5301:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5302:       continue;
                   5303:     }
                   5304:     ne=ne+1;
                   5305:     sumx  += x[i];       
                   5306:     sumx2 += x[i]*x[i];  
                   5307:     sumxy += x[i] * y[i];
                   5308:     sumy  += y[i];      
                   5309:     sumy2 += y[i]*y[i]; 
                   5310:     denom = (ne * sumx2 - sumx*sumx);
                   5311:     /* 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); */
                   5312:   } 
                   5313:   
                   5314:   denom = (ne * sumx2 - sumx*sumx);
                   5315:   if (denom == 0) {
                   5316:     // vertical, slope m is infinity
                   5317:     *b = INFINITY;
                   5318:     *a = 0;
                   5319:     if (r) *r = 0;
                   5320:     return 1;
                   5321:   }
                   5322:   
                   5323:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5324:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5325:   if (r!=NULL) {
                   5326:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5327:       sqrt((sumx2 - sumx*sumx/ne) *
                   5328:           (sumy2 - sumy*sumy/ne));
                   5329:   }
                   5330:   *no=ne;
                   5331:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5332:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5333:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5334:       continue;
                   5335:     }
                   5336:     ne=ne+1;
                   5337:     yhat = y[i] - *a -*b* x[i];
                   5338:     sume2  += yhat * yhat ;       
                   5339:     
                   5340:     denom = (ne * sumx2 - sumx*sumx);
                   5341:     /* 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); */
                   5342:   } 
                   5343:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5344:   *sa= *sb * sqrt(sumx2/ne);
                   5345:   
                   5346:   return 0; 
                   5347: }
                   5348: 
1.126     brouard  5349: /************ Prevalence ********************/
1.227     brouard  5350: 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)
                   5351: {  
                   5352:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5353:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5354:      We still use firstpass and lastpass as another selection.
                   5355:   */
1.126     brouard  5356:  
1.227     brouard  5357:   int i, m, jk, j1, bool, z1,j, iv;
                   5358:   int mi; /* Effective wave */
                   5359:   int iage;
                   5360:   double agebegin, ageend;
                   5361: 
                   5362:   double **prop;
                   5363:   double posprop; 
                   5364:   double  y2; /* in fractional years */
                   5365:   int iagemin, iagemax;
                   5366:   int first; /** to stop verbosity which is redirected to log file */
                   5367: 
                   5368:   iagemin= (int) agemin;
                   5369:   iagemax= (int) agemax;
                   5370:   /*pp=vector(1,nlstate);*/
1.251     brouard  5371:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5372:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5373:   j1=0;
1.222     brouard  5374:   
1.227     brouard  5375:   /*j=cptcoveff;*/
                   5376:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5377:   
1.288     brouard  5378:   first=0;
1.227     brouard  5379:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5380:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5381:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5382:        prop[i][iage]=0.0;
                   5383:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5384:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5385:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5386:     
                   5387:     for (i=1; i<=imx; i++) { /* Each individual */
                   5388:       bool=1;
                   5389:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5390:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5391:        m=mw[mi][i];
                   5392:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5393:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5394:        for (z1=1; z1<=cptcoveff; z1++){
                   5395:          if( Fixed[Tmodelind[z1]]==1){
                   5396:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5397:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5398:              bool=0;
                   5399:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5400:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5401:              bool=0;
                   5402:            }
                   5403:        }
                   5404:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5405:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5406:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5407:          if(m >=firstpass && m <=lastpass){
                   5408:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5409:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5410:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5411:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5412:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5413:                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); 
                   5414:                exit(1);
                   5415:              }
                   5416:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5417:                /*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]]);*/
                   5418:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5419:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5420:              } /* end valid statuses */ 
                   5421:            } /* end selection of dates */
                   5422:          } /* end selection of waves */
                   5423:        } /* end bool */
                   5424:       } /* end wave */
                   5425:     } /* end individual */
                   5426:     for(i=iagemin; i <= iagemax+3; i++){  
                   5427:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5428:        posprop += prop[jk][i]; 
                   5429:       } 
                   5430:       
                   5431:       for(jk=1; jk <=nlstate ; jk++){      
                   5432:        if( i <=  iagemax){ 
                   5433:          if(posprop>=1.e-5){ 
                   5434:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5435:          } else{
1.288     brouard  5436:            if(!first){
                   5437:              first=1;
1.266     brouard  5438:              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]);
                   5439:            }else{
1.288     brouard  5440:              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  5441:            }
                   5442:          }
                   5443:        } 
                   5444:       }/* end jk */ 
                   5445:     }/* end i */ 
1.222     brouard  5446:      /*} *//* end i1 */
1.227     brouard  5447:   } /* end j1 */
1.222     brouard  5448:   
1.227     brouard  5449:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5450:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5451:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5452: }  /* End of prevalence */
1.126     brouard  5453: 
                   5454: /************* Waves Concatenation ***************/
                   5455: 
                   5456: 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)
                   5457: {
1.298     brouard  5458:   /* 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  5459:      Death is a valid wave (if date is known).
                   5460:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5461:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5462:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5463:   */
1.126     brouard  5464: 
1.224     brouard  5465:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5466:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5467:      double sum=0., jmean=0.;*/
1.224     brouard  5468:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5469:   int j, k=0,jk, ju, jl;
                   5470:   double sum=0.;
                   5471:   first=0;
1.214     brouard  5472:   firstwo=0;
1.217     brouard  5473:   firsthree=0;
1.218     brouard  5474:   firstfour=0;
1.164     brouard  5475:   jmin=100000;
1.126     brouard  5476:   jmax=-1;
                   5477:   jmean=0.;
1.224     brouard  5478: 
                   5479: /* Treating live states */
1.214     brouard  5480:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5481:     mi=0;  /* First valid wave */
1.227     brouard  5482:     mli=0; /* Last valid wave */
1.309     brouard  5483:     m=firstpass;  /* Loop on waves */
                   5484:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5485:       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 */
                   5486:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5487:       }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  5488:        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  5489:        mli=m;
1.224     brouard  5490:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5491:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5492:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5493:       }
1.309     brouard  5494:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5495: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5496:        break;
1.224     brouard  5497: #else
1.317     brouard  5498:        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  5499:          if(firsthree == 0){
1.302     brouard  5500:            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  5501:            firsthree=1;
1.317     brouard  5502:          }else if(firsthree >=1 && firsthree < 10){
                   5503:            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);
                   5504:            firsthree++;
                   5505:          }else if(firsthree == 10){
                   5506:            printf("Information, too many Information flags: no more reported to log either\n");
                   5507:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5508:            firsthree++;
                   5509:          }else{
                   5510:            firsthree++;
1.227     brouard  5511:          }
1.309     brouard  5512:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5513:          mli=m;
                   5514:        }
                   5515:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5516:          nbwarn++;
1.309     brouard  5517:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5518:            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);
                   5519:            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);
                   5520:          }
                   5521:          break;
                   5522:        }
                   5523:        break;
1.224     brouard  5524: #endif
1.227     brouard  5525:       }/* End m >= lastpass */
1.126     brouard  5526:     }/* end while */
1.224     brouard  5527: 
1.227     brouard  5528:     /* 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  5529:     /* After last pass */
1.224     brouard  5530: /* Treating death states */
1.214     brouard  5531:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5532:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5533:       /* } */
1.126     brouard  5534:       mi++;    /* Death is another wave */
                   5535:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5536:       /* Only death is a correct wave */
1.126     brouard  5537:       mw[mi][i]=m;
1.257     brouard  5538:     } /* else not in a death state */
1.224     brouard  5539: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5540:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5541:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5542:        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  5543:          nbwarn++;
                   5544:          if(firstfiv==0){
1.309     brouard  5545:            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  5546:            firstfiv=1;
                   5547:          }else{
1.309     brouard  5548:            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  5549:          }
1.309     brouard  5550:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5551:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5552:          nberr++;
                   5553:          if(firstwo==0){
1.309     brouard  5554:            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  5555:            firstwo=1;
                   5556:          }
1.309     brouard  5557:          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  5558:        }
1.257     brouard  5559:       }else{ /* if date of interview is unknown */
1.227     brouard  5560:        /* death is known but not confirmed by death status at any wave */
                   5561:        if(firstfour==0){
1.309     brouard  5562:          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  5563:          firstfour=1;
                   5564:        }
1.309     brouard  5565:        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  5566:       }
1.224     brouard  5567:     } /* end if date of death is known */
                   5568: #endif
1.309     brouard  5569:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5570:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5571:     if(mi==0){
                   5572:       nbwarn++;
                   5573:       if(first==0){
1.227     brouard  5574:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5575:        first=1;
1.126     brouard  5576:       }
                   5577:       if(first==1){
1.227     brouard  5578:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5579:       }
                   5580:     } /* end mi==0 */
                   5581:   } /* End individuals */
1.214     brouard  5582:   /* wav and mw are no more changed */
1.223     brouard  5583:        
1.317     brouard  5584:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5585:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5586: 
                   5587: 
1.126     brouard  5588:   for(i=1; i<=imx; i++){
                   5589:     for(mi=1; mi<wav[i];mi++){
                   5590:       if (stepm <=0)
1.227     brouard  5591:        dh[mi][i]=1;
1.126     brouard  5592:       else{
1.260     brouard  5593:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5594:          if (agedc[i] < 2*AGESUP) {
                   5595:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5596:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5597:            else if(j<0){
                   5598:              nberr++;
                   5599:              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]);
                   5600:              j=1; /* Temporary Dangerous patch */
                   5601:              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);
                   5602:              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]);
                   5603:              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);
                   5604:            }
                   5605:            k=k+1;
                   5606:            if (j >= jmax){
                   5607:              jmax=j;
                   5608:              ijmax=i;
                   5609:            }
                   5610:            if (j <= jmin){
                   5611:              jmin=j;
                   5612:              ijmin=i;
                   5613:            }
                   5614:            sum=sum+j;
                   5615:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5616:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5617:          }
                   5618:        }
                   5619:        else{
                   5620:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5621: /*       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  5622:                                        
1.227     brouard  5623:          k=k+1;
                   5624:          if (j >= jmax) {
                   5625:            jmax=j;
                   5626:            ijmax=i;
                   5627:          }
                   5628:          else if (j <= jmin){
                   5629:            jmin=j;
                   5630:            ijmin=i;
                   5631:          }
                   5632:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5633:          /*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]);*/
                   5634:          if(j<0){
                   5635:            nberr++;
                   5636:            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]);
                   5637:            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]);
                   5638:          }
                   5639:          sum=sum+j;
                   5640:        }
                   5641:        jk= j/stepm;
                   5642:        jl= j -jk*stepm;
                   5643:        ju= j -(jk+1)*stepm;
                   5644:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5645:          if(jl==0){
                   5646:            dh[mi][i]=jk;
                   5647:            bh[mi][i]=0;
                   5648:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5649:                  * to avoid the price of an extra matrix product in likelihood */
                   5650:            dh[mi][i]=jk+1;
                   5651:            bh[mi][i]=ju;
                   5652:          }
                   5653:        }else{
                   5654:          if(jl <= -ju){
                   5655:            dh[mi][i]=jk;
                   5656:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5657:                                 * is higher than the multiple of stepm and negative otherwise.
                   5658:                                 */
                   5659:          }
                   5660:          else{
                   5661:            dh[mi][i]=jk+1;
                   5662:            bh[mi][i]=ju;
                   5663:          }
                   5664:          if(dh[mi][i]==0){
                   5665:            dh[mi][i]=1; /* At least one step */
                   5666:            bh[mi][i]=ju; /* At least one step */
                   5667:            /*  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);*/
                   5668:          }
                   5669:        } /* end if mle */
1.126     brouard  5670:       }
                   5671:     } /* end wave */
                   5672:   }
                   5673:   jmean=sum/k;
                   5674:   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  5675:   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  5676: }
1.126     brouard  5677: 
                   5678: /*********** Tricode ****************************/
1.220     brouard  5679:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5680:  {
                   5681:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5682:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5683:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5684:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5685:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5686:     */
1.130     brouard  5687: 
1.242     brouard  5688:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5689:    int modmaxcovj=0; /* Modality max of covariates j */
                   5690:    int cptcode=0; /* Modality max of covariates j */
                   5691:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5692: 
                   5693: 
1.242     brouard  5694:    /* cptcoveff=0;  */
                   5695:    /* *cptcov=0; */
1.126     brouard  5696:  
1.242     brouard  5697:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5698:    for (k=1; k <= maxncov; k++)
                   5699:      for(j=1; j<=2; j++)
                   5700:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5701: 
1.242     brouard  5702:    /* Loop on covariates without age and products and no quantitative variable */
                   5703:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5704:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5705:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5706:        switch(Fixed[k]) {
                   5707:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5708:         modmaxcovj=0;
                   5709:         modmincovj=0;
1.242     brouard  5710:         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*/
                   5711:           ij=(int)(covar[Tvar[k]][i]);
                   5712:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5713:            * If product of Vn*Vm, still boolean *:
                   5714:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5715:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5716:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5717:              modality of the nth covariate of individual i. */
                   5718:           if (ij > modmaxcovj)
                   5719:             modmaxcovj=ij; 
                   5720:           else if (ij < modmincovj) 
                   5721:             modmincovj=ij; 
1.287     brouard  5722:           if (ij <0 || ij >1 ){
1.311     brouard  5723:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5724:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5725:             fflush(ficlog);
                   5726:             exit(1);
1.287     brouard  5727:           }
                   5728:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5729:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5730:             exit(1);
                   5731:           }else
                   5732:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5733:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5734:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5735:           /* getting the maximum value of the modality of the covariate
                   5736:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5737:              female ies 1, then modmaxcovj=1.
                   5738:           */
                   5739:         } /* end for loop on individuals i */
                   5740:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5741:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5742:         cptcode=modmaxcovj;
                   5743:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5744:         /*for (i=0; i<=cptcode; i++) {*/
                   5745:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5746:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5747:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5748:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5749:             if( j != -1){
                   5750:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5751:                                  covariate for which somebody answered excluding 
                   5752:                                  undefined. Usually 2: 0 and 1. */
                   5753:             }
                   5754:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5755:                                     covariate for which somebody answered including 
                   5756:                                     undefined. Usually 3: -1, 0 and 1. */
                   5757:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5758:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5759:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5760:                        
1.242     brouard  5761:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5762:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5763:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5764:         /* modmincovj=3; modmaxcovj = 7; */
                   5765:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5766:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5767:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5768:         /* nbcode[Tvar[j]][ij]=k; */
                   5769:         /* nbcode[Tvar[j]][1]=0; */
                   5770:         /* nbcode[Tvar[j]][2]=1; */
                   5771:         /* nbcode[Tvar[j]][3]=2; */
                   5772:         /* To be continued (not working yet). */
                   5773:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5774: 
                   5775:         /* 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*/
                   5776:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5777:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5778:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5779:         /*, could be restored in the future */
                   5780:         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  5781:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5782:             break;
                   5783:           }
                   5784:           ij++;
1.287     brouard  5785:           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  5786:           cptcode = ij; /* New max modality for covar j */
                   5787:         } /* end of loop on modality i=-1 to 1 or more */
                   5788:         break;
                   5789:        case 1: /* Testing on varying covariate, could be simple and
                   5790:                * should look at waves or product of fixed *
                   5791:                * varying. No time to test -1, assuming 0 and 1 only */
                   5792:         ij=0;
                   5793:         for(i=0; i<=1;i++){
                   5794:           nbcode[Tvar[k]][++ij]=i;
                   5795:         }
                   5796:         break;
                   5797:        default:
                   5798:         break;
                   5799:        } /* end switch */
                   5800:      } /* end dummy test */
1.311     brouard  5801:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5802:        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*/
                   5803:         if(isnan(covar[Tvar[k]][i])){
                   5804:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5805:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5806:           fflush(ficlog);
                   5807:           exit(1);
                   5808:          }
                   5809:        }
                   5810:      }
1.287     brouard  5811:    } /* 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  5812:   
                   5813:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5814:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5815:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5816:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5817:      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 */ 
                   5818:      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 */
                   5819:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5820:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5821:   
                   5822:    ij=0;
                   5823:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5824:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5825:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5826:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5827:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5828:        /* If product not in single variable we don't print results */
                   5829:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5830:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5831:        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*/
                   5832:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5833:        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 */
                   5834:        if(Fixed[k]!=0)
                   5835:         anyvaryingduminmodel=1;
                   5836:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5837:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5838:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5839:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5840:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5841:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5842:      } 
                   5843:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5844:    /* ij--; */
                   5845:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5846:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5847:                * because they can be excluded from the model and real
                   5848:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5849:    for(j=ij+1; j<= cptcovt; j++){
                   5850:      Tvaraff[j]=0;
                   5851:      Tmodelind[j]=0;
                   5852:    }
                   5853:    for(j=ntveff+1; j<= cptcovt; j++){
                   5854:      TmodelInvind[j]=0;
                   5855:    }
                   5856:    /* To be sorted */
                   5857:    ;
                   5858:  }
1.126     brouard  5859: 
1.145     brouard  5860: 
1.126     brouard  5861: /*********** Health Expectancies ****************/
                   5862: 
1.235     brouard  5863:  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  5864: 
                   5865: {
                   5866:   /* Health expectancies, no variances */
1.164     brouard  5867:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5868:   int nhstepma, nstepma; /* Decreasing with age */
                   5869:   double age, agelim, hf;
                   5870:   double ***p3mat;
                   5871:   double eip;
                   5872: 
1.238     brouard  5873:   /* pstamp(ficreseij); */
1.126     brouard  5874:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5875:   fprintf(ficreseij,"# Age");
                   5876:   for(i=1; i<=nlstate;i++){
                   5877:     for(j=1; j<=nlstate;j++){
                   5878:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5879:     }
                   5880:     fprintf(ficreseij," e%1d. ",i);
                   5881:   }
                   5882:   fprintf(ficreseij,"\n");
                   5883: 
                   5884:   
                   5885:   if(estepm < stepm){
                   5886:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5887:   }
                   5888:   else  hstepm=estepm;   
                   5889:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5890:    * This is mainly to measure the difference between two models: for example
                   5891:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5892:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5893:    * progression in between and thus overestimating or underestimating according
                   5894:    * to the curvature of the survival function. If, for the same date, we 
                   5895:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5896:    * to compare the new estimate of Life expectancy with the same linear 
                   5897:    * hypothesis. A more precise result, taking into account a more precise
                   5898:    * curvature will be obtained if estepm is as small as stepm. */
                   5899: 
                   5900:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5901:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5902:      nhstepm is the number of hstepm from age to agelim 
                   5903:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5904:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5905:      and note for a fixed period like estepm months */
                   5906:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5907:      survival function given by stepm (the optimization length). Unfortunately it
                   5908:      means that if the survival funtion is printed only each two years of age and if
                   5909:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5910:      results. So we changed our mind and took the option of the best precision.
                   5911:   */
                   5912:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5913: 
                   5914:   agelim=AGESUP;
                   5915:   /* If stepm=6 months */
                   5916:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5917:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5918:     
                   5919: /* nhstepm age range expressed in number of stepm */
                   5920:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5921:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5922:   /* if (stepm >= YEARM) hstepm=1;*/
                   5923:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5924:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5925: 
                   5926:   for (age=bage; age<=fage; age ++){ 
                   5927:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5928:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5929:     /* if (stepm >= YEARM) hstepm=1;*/
                   5930:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5931: 
                   5932:     /* If stepm=6 months */
                   5933:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5934:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5935:     
1.235     brouard  5936:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5937:     
                   5938:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5939:     
                   5940:     printf("%d|",(int)age);fflush(stdout);
                   5941:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5942:     
                   5943:     /* Computing expectancies */
                   5944:     for(i=1; i<=nlstate;i++)
                   5945:       for(j=1; j<=nlstate;j++)
                   5946:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5947:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5948:          
                   5949:          /* 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]);*/
                   5950: 
                   5951:        }
                   5952: 
                   5953:     fprintf(ficreseij,"%3.0f",age );
                   5954:     for(i=1; i<=nlstate;i++){
                   5955:       eip=0;
                   5956:       for(j=1; j<=nlstate;j++){
                   5957:        eip +=eij[i][j][(int)age];
                   5958:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5959:       }
                   5960:       fprintf(ficreseij,"%9.4f", eip );
                   5961:     }
                   5962:     fprintf(ficreseij,"\n");
                   5963:     
                   5964:   }
                   5965:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5966:   printf("\n");
                   5967:   fprintf(ficlog,"\n");
                   5968:   
                   5969: }
                   5970: 
1.235     brouard  5971:  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  5972: 
                   5973: {
                   5974:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5975:      to initial status i, ei. .
1.126     brouard  5976:   */
                   5977:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5978:   int nhstepma, nstepma; /* Decreasing with age */
                   5979:   double age, agelim, hf;
                   5980:   double ***p3matp, ***p3matm, ***varhe;
                   5981:   double **dnewm,**doldm;
                   5982:   double *xp, *xm;
                   5983:   double **gp, **gm;
                   5984:   double ***gradg, ***trgradg;
                   5985:   int theta;
                   5986: 
                   5987:   double eip, vip;
                   5988: 
                   5989:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5990:   xp=vector(1,npar);
                   5991:   xm=vector(1,npar);
                   5992:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5993:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5994:   
                   5995:   pstamp(ficresstdeij);
                   5996:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5997:   fprintf(ficresstdeij,"# Age");
                   5998:   for(i=1; i<=nlstate;i++){
                   5999:     for(j=1; j<=nlstate;j++)
                   6000:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6001:     fprintf(ficresstdeij," e%1d. ",i);
                   6002:   }
                   6003:   fprintf(ficresstdeij,"\n");
                   6004: 
                   6005:   pstamp(ficrescveij);
                   6006:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6007:   fprintf(ficrescveij,"# Age");
                   6008:   for(i=1; i<=nlstate;i++)
                   6009:     for(j=1; j<=nlstate;j++){
                   6010:       cptj= (j-1)*nlstate+i;
                   6011:       for(i2=1; i2<=nlstate;i2++)
                   6012:        for(j2=1; j2<=nlstate;j2++){
                   6013:          cptj2= (j2-1)*nlstate+i2;
                   6014:          if(cptj2 <= cptj)
                   6015:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6016:        }
                   6017:     }
                   6018:   fprintf(ficrescveij,"\n");
                   6019:   
                   6020:   if(estepm < stepm){
                   6021:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6022:   }
                   6023:   else  hstepm=estepm;   
                   6024:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6025:    * This is mainly to measure the difference between two models: for example
                   6026:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6027:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6028:    * progression in between and thus overestimating or underestimating according
                   6029:    * to the curvature of the survival function. If, for the same date, we 
                   6030:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6031:    * to compare the new estimate of Life expectancy with the same linear 
                   6032:    * hypothesis. A more precise result, taking into account a more precise
                   6033:    * curvature will be obtained if estepm is as small as stepm. */
                   6034: 
                   6035:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6036:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6037:      nhstepm is the number of hstepm from age to agelim 
                   6038:      nstepm is the number of stepm from age to agelin. 
                   6039:      Look at hpijx to understand the reason of that which relies in memory size
                   6040:      and note for a fixed period like estepm months */
                   6041:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6042:      survival function given by stepm (the optimization length). Unfortunately it
                   6043:      means that if the survival funtion is printed only each two years of age and if
                   6044:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6045:      results. So we changed our mind and took the option of the best precision.
                   6046:   */
                   6047:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6048: 
                   6049:   /* If stepm=6 months */
                   6050:   /* nhstepm age range expressed in number of stepm */
                   6051:   agelim=AGESUP;
                   6052:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6053:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6054:   /* if (stepm >= YEARM) hstepm=1;*/
                   6055:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6056:   
                   6057:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6058:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6059:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6060:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6061:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6062:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6063: 
                   6064:   for (age=bage; age<=fage; age ++){ 
                   6065:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6066:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6067:     /* if (stepm >= YEARM) hstepm=1;*/
                   6068:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6069:                
1.126     brouard  6070:     /* If stepm=6 months */
                   6071:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6072:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6073:     
                   6074:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6075:                
1.126     brouard  6076:     /* Computing  Variances of health expectancies */
                   6077:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6078:        decrease memory allocation */
                   6079:     for(theta=1; theta <=npar; theta++){
                   6080:       for(i=1; i<=npar; i++){ 
1.222     brouard  6081:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6082:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6083:       }
1.235     brouard  6084:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6085:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6086:                        
1.126     brouard  6087:       for(j=1; j<= nlstate; j++){
1.222     brouard  6088:        for(i=1; i<=nlstate; i++){
                   6089:          for(h=0; h<=nhstepm-1; h++){
                   6090:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6091:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6092:          }
                   6093:        }
1.126     brouard  6094:       }
1.218     brouard  6095:                        
1.126     brouard  6096:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6097:        for(h=0; h<=nhstepm-1; h++){
                   6098:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6099:        }
1.126     brouard  6100:     }/* End theta */
                   6101:     
                   6102:     
                   6103:     for(h=0; h<=nhstepm-1; h++)
                   6104:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6105:        for(theta=1; theta <=npar; theta++)
                   6106:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6107:     
1.218     brouard  6108:                
1.222     brouard  6109:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6110:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6111:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6112:                
1.222     brouard  6113:     printf("%d|",(int)age);fflush(stdout);
                   6114:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6115:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6116:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6117:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6118:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6119:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6120:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6121:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6122:       }
                   6123:     }
1.320     brouard  6124:     /* if((int)age ==50){ */
                   6125:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6126:     /* } */
1.126     brouard  6127:     /* Computing expectancies */
1.235     brouard  6128:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6129:     for(i=1; i<=nlstate;i++)
                   6130:       for(j=1; j<=nlstate;j++)
1.222     brouard  6131:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6132:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6133:                                        
1.222     brouard  6134:          /* 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  6135:                                        
1.222     brouard  6136:        }
1.269     brouard  6137: 
                   6138:     /* Standard deviation of expectancies ij */                
1.126     brouard  6139:     fprintf(ficresstdeij,"%3.0f",age );
                   6140:     for(i=1; i<=nlstate;i++){
                   6141:       eip=0.;
                   6142:       vip=0.;
                   6143:       for(j=1; j<=nlstate;j++){
1.222     brouard  6144:        eip += eij[i][j][(int)age];
                   6145:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6146:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6147:        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  6148:       }
                   6149:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6150:     }
                   6151:     fprintf(ficresstdeij,"\n");
1.218     brouard  6152:                
1.269     brouard  6153:     /* Variance of expectancies ij */          
1.126     brouard  6154:     fprintf(ficrescveij,"%3.0f",age );
                   6155:     for(i=1; i<=nlstate;i++)
                   6156:       for(j=1; j<=nlstate;j++){
1.222     brouard  6157:        cptj= (j-1)*nlstate+i;
                   6158:        for(i2=1; i2<=nlstate;i2++)
                   6159:          for(j2=1; j2<=nlstate;j2++){
                   6160:            cptj2= (j2-1)*nlstate+i2;
                   6161:            if(cptj2 <= cptj)
                   6162:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6163:          }
1.126     brouard  6164:       }
                   6165:     fprintf(ficrescveij,"\n");
1.218     brouard  6166:                
1.126     brouard  6167:   }
                   6168:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6169:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6170:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6171:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6172:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6173:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6174:   printf("\n");
                   6175:   fprintf(ficlog,"\n");
1.218     brouard  6176:        
1.126     brouard  6177:   free_vector(xm,1,npar);
                   6178:   free_vector(xp,1,npar);
                   6179:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6180:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6181:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6182: }
1.218     brouard  6183:  
1.126     brouard  6184: /************ Variance ******************/
1.235     brouard  6185:  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  6186:  {
1.279     brouard  6187:    /** Variance of health expectancies 
                   6188:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6189:     * double **newm;
                   6190:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6191:     */
1.218     brouard  6192:   
                   6193:    /* int movingaverage(); */
                   6194:    double **dnewm,**doldm;
                   6195:    double **dnewmp,**doldmp;
                   6196:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6197:    int first=0;
1.218     brouard  6198:    int k;
                   6199:    double *xp;
1.279     brouard  6200:    double **gp, **gm;  /**< for var eij */
                   6201:    double ***gradg, ***trgradg; /**< for var eij */
                   6202:    double **gradgp, **trgradgp; /**< for var p point j */
                   6203:    double *gpp, *gmp; /**< for var p point j */
                   6204:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6205:    double ***p3mat;
                   6206:    double age,agelim, hf;
                   6207:    /* double ***mobaverage; */
                   6208:    int theta;
                   6209:    char digit[4];
                   6210:    char digitp[25];
                   6211: 
                   6212:    char fileresprobmorprev[FILENAMELENGTH];
                   6213: 
                   6214:    if(popbased==1){
                   6215:      if(mobilav!=0)
                   6216:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6217:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6218:    }
                   6219:    else 
                   6220:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6221: 
1.218     brouard  6222:    /* if (mobilav!=0) { */
                   6223:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6224:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6225:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6226:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6227:    /*   } */
                   6228:    /* } */
                   6229: 
                   6230:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6231:    sprintf(digit,"%-d",ij);
                   6232:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6233:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6234:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6235:    strcat(fileresprobmorprev,fileresu);
                   6236:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6237:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6238:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6239:    }
                   6240:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6241:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6242:    pstamp(ficresprobmorprev);
                   6243:    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  6244:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6245:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6246:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6247:    }
                   6248:    for(j=1;j<=cptcoveff;j++) 
                   6249:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   6250:    fprintf(ficresprobmorprev,"\n");
                   6251: 
1.218     brouard  6252:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6253:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6254:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6255:      for(i=1; i<=nlstate;i++)
                   6256:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6257:    }  
                   6258:    fprintf(ficresprobmorprev,"\n");
                   6259:   
                   6260:    fprintf(ficgp,"\n# Routine varevsij");
                   6261:    fprintf(ficgp,"\nunset title \n");
                   6262:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6263:    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");
                   6264:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6265: 
1.218     brouard  6266:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6267:    pstamp(ficresvij);
                   6268:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6269:    if(popbased==1)
                   6270:      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);
                   6271:    else
                   6272:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6273:    fprintf(ficresvij,"# Age");
                   6274:    for(i=1; i<=nlstate;i++)
                   6275:      for(j=1; j<=nlstate;j++)
                   6276:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6277:    fprintf(ficresvij,"\n");
                   6278: 
                   6279:    xp=vector(1,npar);
                   6280:    dnewm=matrix(1,nlstate,1,npar);
                   6281:    doldm=matrix(1,nlstate,1,nlstate);
                   6282:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6283:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6284: 
                   6285:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6286:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6287:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6288:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6289:   
1.218     brouard  6290:    if(estepm < stepm){
                   6291:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6292:    }
                   6293:    else  hstepm=estepm;   
                   6294:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6295:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6296:       nhstepm is the number of hstepm from age to agelim 
                   6297:       nstepm is the number of stepm from age to agelim. 
                   6298:       Look at function hpijx to understand why because of memory size limitations, 
                   6299:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6300:       survival function given by stepm (the optimization length). Unfortunately it
                   6301:       means that if the survival funtion is printed every two years of age and if
                   6302:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6303:       results. So we changed our mind and took the option of the best precision.
                   6304:    */
                   6305:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6306:    agelim = AGESUP;
                   6307:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6308:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6309:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6310:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6311:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6312:      gp=matrix(0,nhstepm,1,nlstate);
                   6313:      gm=matrix(0,nhstepm,1,nlstate);
                   6314:                
                   6315:                
                   6316:      for(theta=1; theta <=npar; theta++){
                   6317:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6318:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6319:        }
1.279     brouard  6320:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6321:        * returns into prlim .
1.288     brouard  6322:        */
1.242     brouard  6323:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6324: 
                   6325:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6326:        if (popbased==1) {
                   6327:         if(mobilav ==0){
                   6328:           for(i=1; i<=nlstate;i++)
                   6329:             prlim[i][i]=probs[(int)age][i][ij];
                   6330:         }else{ /* mobilav */ 
                   6331:           for(i=1; i<=nlstate;i++)
                   6332:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6333:         }
                   6334:        }
1.295     brouard  6335:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6336:        */                      
                   6337:        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  6338:        /**< 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  6339:        * at horizon h in state j including mortality.
                   6340:        */
1.218     brouard  6341:        for(j=1; j<= nlstate; j++){
                   6342:         for(h=0; h<=nhstepm; h++){
                   6343:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6344:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6345:         }
                   6346:        }
1.279     brouard  6347:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6348:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6349:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6350:        */
                   6351:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6352:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6353:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6354:        }
                   6355:        
                   6356:        /* Again with minus shift */
1.218     brouard  6357:                        
                   6358:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6359:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6360: 
1.242     brouard  6361:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6362:                        
                   6363:        if (popbased==1) {
                   6364:         if(mobilav ==0){
                   6365:           for(i=1; i<=nlstate;i++)
                   6366:             prlim[i][i]=probs[(int)age][i][ij];
                   6367:         }else{ /* mobilav */ 
                   6368:           for(i=1; i<=nlstate;i++)
                   6369:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6370:         }
                   6371:        }
                   6372:                        
1.235     brouard  6373:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6374:                        
                   6375:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6376:         for(h=0; h<=nhstepm; h++){
                   6377:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6378:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6379:         }
                   6380:        }
                   6381:        /* This for computing probability of death (h=1 means
                   6382:          computed over hstepm matrices product = hstepm*stepm months) 
                   6383:          as a weighted average of prlim.
                   6384:        */
                   6385:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6386:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6387:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6388:        }    
1.279     brouard  6389:        /* end shifting computations */
                   6390: 
                   6391:        /**< Computing gradient matrix at horizon h 
                   6392:        */
1.218     brouard  6393:        for(j=1; j<= nlstate; j++) /* vareij */
                   6394:         for(h=0; h<=nhstepm; h++){
                   6395:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6396:         }
1.279     brouard  6397:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6398:        */
                   6399:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6400:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6401:        }
                   6402:                        
                   6403:      } /* End theta */
1.279     brouard  6404:      
                   6405:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6406:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6407:                
                   6408:      for(h=0; h<=nhstepm; h++) /* veij */
                   6409:        for(j=1; j<=nlstate;j++)
                   6410:         for(theta=1; theta <=npar; theta++)
                   6411:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6412:                
                   6413:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6414:        for(theta=1; theta <=npar; theta++)
                   6415:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6416:      /**< as well as its transposed matrix 
                   6417:       */               
1.218     brouard  6418:                
                   6419:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6420:      for(i=1;i<=nlstate;i++)
                   6421:        for(j=1;j<=nlstate;j++)
                   6422:         vareij[i][j][(int)age] =0.;
1.279     brouard  6423: 
                   6424:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6425:       * and k (nhstepm) formula 15 of article
                   6426:       * Lievre-Brouard-Heathcote
                   6427:       */
                   6428:      
1.218     brouard  6429:      for(h=0;h<=nhstepm;h++){
                   6430:        for(k=0;k<=nhstepm;k++){
                   6431:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6432:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6433:         for(i=1;i<=nlstate;i++)
                   6434:           for(j=1;j<=nlstate;j++)
                   6435:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6436:        }
                   6437:      }
                   6438:                
1.279     brouard  6439:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6440:       * p.j overall mortality formula 49 but computed directly because
                   6441:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6442:       * wix is independent of theta.
                   6443:       */
1.218     brouard  6444:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6445:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6446:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6447:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6448:         varppt[j][i]=doldmp[j][i];
                   6449:      /* end ppptj */
                   6450:      /*  x centered again */
                   6451:                
1.242     brouard  6452:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6453:                
                   6454:      if (popbased==1) {
                   6455:        if(mobilav ==0){
                   6456:         for(i=1; i<=nlstate;i++)
                   6457:           prlim[i][i]=probs[(int)age][i][ij];
                   6458:        }else{ /* mobilav */ 
                   6459:         for(i=1; i<=nlstate;i++)
                   6460:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6461:        }
                   6462:      }
                   6463:                
                   6464:      /* This for computing probability of death (h=1 means
                   6465:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6466:        as a weighted average of prlim.
                   6467:      */
1.235     brouard  6468:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6469:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6470:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6471:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6472:      }    
                   6473:      /* end probability of death */
                   6474:                
                   6475:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6476:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6477:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6478:        for(i=1; i<=nlstate;i++){
                   6479:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6480:        }
                   6481:      } 
                   6482:      fprintf(ficresprobmorprev,"\n");
                   6483:                
                   6484:      fprintf(ficresvij,"%.0f ",age );
                   6485:      for(i=1; i<=nlstate;i++)
                   6486:        for(j=1; j<=nlstate;j++){
                   6487:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6488:        }
                   6489:      fprintf(ficresvij,"\n");
                   6490:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6491:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6492:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6493:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6494:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6495:    } /* End age */
                   6496:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6497:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6498:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6499:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6500:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6501:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6502:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6503:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6504:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6505:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6506:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6507:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6508:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6509:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6510:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6511:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6512:    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);
                   6513:    /*  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  6514:     */
1.218     brouard  6515:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6516:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6517: 
1.218     brouard  6518:    free_vector(xp,1,npar);
                   6519:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6520:    free_matrix(dnewm,1,nlstate,1,npar);
                   6521:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6522:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6523:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6524:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6525:    fclose(ficresprobmorprev);
                   6526:    fflush(ficgp);
                   6527:    fflush(fichtm); 
                   6528:  }  /* end varevsij */
1.126     brouard  6529: 
                   6530: /************ Variance of prevlim ******************/
1.269     brouard  6531:  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  6532: {
1.205     brouard  6533:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6534:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6535: 
1.268     brouard  6536:   double **dnewmpar,**doldm;
1.126     brouard  6537:   int i, j, nhstepm, hstepm;
                   6538:   double *xp;
                   6539:   double *gp, *gm;
                   6540:   double **gradg, **trgradg;
1.208     brouard  6541:   double **mgm, **mgp;
1.126     brouard  6542:   double age,agelim;
                   6543:   int theta;
                   6544:   
                   6545:   pstamp(ficresvpl);
1.288     brouard  6546:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6547:   fprintf(ficresvpl,"# Age ");
                   6548:   if(nresult >=1)
                   6549:     fprintf(ficresvpl," Result# ");
1.126     brouard  6550:   for(i=1; i<=nlstate;i++)
                   6551:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6552:   fprintf(ficresvpl,"\n");
                   6553: 
                   6554:   xp=vector(1,npar);
1.268     brouard  6555:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6556:   doldm=matrix(1,nlstate,1,nlstate);
                   6557:   
                   6558:   hstepm=1*YEARM; /* Every year of age */
                   6559:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6560:   agelim = AGESUP;
                   6561:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6562:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6563:     if (stepm >= YEARM) hstepm=1;
                   6564:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6565:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6566:     mgp=matrix(1,npar,1,nlstate);
                   6567:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6568:     gp=vector(1,nlstate);
                   6569:     gm=vector(1,nlstate);
                   6570: 
                   6571:     for(theta=1; theta <=npar; theta++){
                   6572:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6573:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6574:       }
1.288     brouard  6575:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6576:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6577:       /* else */
                   6578:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6579:       for(i=1;i<=nlstate;i++){
1.126     brouard  6580:        gp[i] = prlim[i][i];
1.208     brouard  6581:        mgp[theta][i] = prlim[i][i];
                   6582:       }
1.126     brouard  6583:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6584:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6585:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6586:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6587:       /* else */
                   6588:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6589:       for(i=1;i<=nlstate;i++){
1.126     brouard  6590:        gm[i] = prlim[i][i];
1.208     brouard  6591:        mgm[theta][i] = prlim[i][i];
                   6592:       }
1.126     brouard  6593:       for(i=1;i<=nlstate;i++)
                   6594:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6595:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6596:     } /* End theta */
                   6597: 
                   6598:     trgradg =matrix(1,nlstate,1,npar);
                   6599: 
                   6600:     for(j=1; j<=nlstate;j++)
                   6601:       for(theta=1; theta <=npar; theta++)
                   6602:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6603:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6604:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6605:     /*   for(j=1; j<=nlstate;j++){ */
                   6606:     /*         printf(" %d ",j); */
                   6607:     /*         for(theta=1; theta <=npar; theta++) */
                   6608:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6609:     /*         printf("\n "); */
                   6610:     /*   } */
                   6611:     /* } */
                   6612:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6613:     /*   printf("\n gradg %d ",(int)age); */
                   6614:     /*   for(j=1; j<=nlstate;j++){ */
                   6615:     /*         printf("%d ",j); */
                   6616:     /*         for(theta=1; theta <=npar; theta++) */
                   6617:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6618:     /*         printf("\n "); */
                   6619:     /*   } */
                   6620:     /* } */
1.126     brouard  6621: 
                   6622:     for(i=1;i<=nlstate;i++)
                   6623:       varpl[i][(int)age] =0.;
1.209     brouard  6624:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6625:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6626:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6627:     }else{
1.268     brouard  6628:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6629:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6630:     }
1.126     brouard  6631:     for(i=1;i<=nlstate;i++)
                   6632:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6633: 
                   6634:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6635:     if(nresult >=1)
                   6636:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6637:     for(i=1; i<=nlstate;i++){
1.126     brouard  6638:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6639:       /* for(j=1;j<=nlstate;j++) */
                   6640:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6641:     }
1.126     brouard  6642:     fprintf(ficresvpl,"\n");
                   6643:     free_vector(gp,1,nlstate);
                   6644:     free_vector(gm,1,nlstate);
1.208     brouard  6645:     free_matrix(mgm,1,npar,1,nlstate);
                   6646:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6647:     free_matrix(gradg,1,npar,1,nlstate);
                   6648:     free_matrix(trgradg,1,nlstate,1,npar);
                   6649:   } /* End age */
                   6650: 
                   6651:   free_vector(xp,1,npar);
                   6652:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6653:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6654: 
                   6655: }
                   6656: 
                   6657: 
                   6658: /************ Variance of backprevalence limit ******************/
1.269     brouard  6659:  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  6660: {
                   6661:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6662:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6663: 
                   6664:   double **dnewmpar,**doldm;
                   6665:   int i, j, nhstepm, hstepm;
                   6666:   double *xp;
                   6667:   double *gp, *gm;
                   6668:   double **gradg, **trgradg;
                   6669:   double **mgm, **mgp;
                   6670:   double age,agelim;
                   6671:   int theta;
                   6672:   
                   6673:   pstamp(ficresvbl);
                   6674:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6675:   fprintf(ficresvbl,"# Age ");
                   6676:   if(nresult >=1)
                   6677:     fprintf(ficresvbl," Result# ");
                   6678:   for(i=1; i<=nlstate;i++)
                   6679:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6680:   fprintf(ficresvbl,"\n");
                   6681: 
                   6682:   xp=vector(1,npar);
                   6683:   dnewmpar=matrix(1,nlstate,1,npar);
                   6684:   doldm=matrix(1,nlstate,1,nlstate);
                   6685:   
                   6686:   hstepm=1*YEARM; /* Every year of age */
                   6687:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6688:   agelim = AGEINF;
                   6689:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6690:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6691:     if (stepm >= YEARM) hstepm=1;
                   6692:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6693:     gradg=matrix(1,npar,1,nlstate);
                   6694:     mgp=matrix(1,npar,1,nlstate);
                   6695:     mgm=matrix(1,npar,1,nlstate);
                   6696:     gp=vector(1,nlstate);
                   6697:     gm=vector(1,nlstate);
                   6698: 
                   6699:     for(theta=1; theta <=npar; theta++){
                   6700:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6701:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6702:       }
                   6703:       if(mobilavproj > 0 )
                   6704:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6705:       else
                   6706:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6707:       for(i=1;i<=nlstate;i++){
                   6708:        gp[i] = bprlim[i][i];
                   6709:        mgp[theta][i] = bprlim[i][i];
                   6710:       }
                   6711:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6712:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6713:        if(mobilavproj > 0 )
                   6714:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6715:        else
                   6716:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6717:       for(i=1;i<=nlstate;i++){
                   6718:        gm[i] = bprlim[i][i];
                   6719:        mgm[theta][i] = bprlim[i][i];
                   6720:       }
                   6721:       for(i=1;i<=nlstate;i++)
                   6722:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6723:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6724:     } /* End theta */
                   6725: 
                   6726:     trgradg =matrix(1,nlstate,1,npar);
                   6727: 
                   6728:     for(j=1; j<=nlstate;j++)
                   6729:       for(theta=1; theta <=npar; theta++)
                   6730:        trgradg[j][theta]=gradg[theta][j];
                   6731:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6732:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6733:     /*   for(j=1; j<=nlstate;j++){ */
                   6734:     /*         printf(" %d ",j); */
                   6735:     /*         for(theta=1; theta <=npar; theta++) */
                   6736:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6737:     /*         printf("\n "); */
                   6738:     /*   } */
                   6739:     /* } */
                   6740:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6741:     /*   printf("\n gradg %d ",(int)age); */
                   6742:     /*   for(j=1; j<=nlstate;j++){ */
                   6743:     /*         printf("%d ",j); */
                   6744:     /*         for(theta=1; theta <=npar; theta++) */
                   6745:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6746:     /*         printf("\n "); */
                   6747:     /*   } */
                   6748:     /* } */
                   6749: 
                   6750:     for(i=1;i<=nlstate;i++)
                   6751:       varbpl[i][(int)age] =0.;
                   6752:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6753:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6754:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6755:     }else{
                   6756:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6757:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6758:     }
                   6759:     for(i=1;i<=nlstate;i++)
                   6760:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6761: 
                   6762:     fprintf(ficresvbl,"%.0f ",age );
                   6763:     if(nresult >=1)
                   6764:       fprintf(ficresvbl,"%d ",nres );
                   6765:     for(i=1; i<=nlstate;i++)
                   6766:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6767:     fprintf(ficresvbl,"\n");
                   6768:     free_vector(gp,1,nlstate);
                   6769:     free_vector(gm,1,nlstate);
                   6770:     free_matrix(mgm,1,npar,1,nlstate);
                   6771:     free_matrix(mgp,1,npar,1,nlstate);
                   6772:     free_matrix(gradg,1,npar,1,nlstate);
                   6773:     free_matrix(trgradg,1,nlstate,1,npar);
                   6774:   } /* End age */
                   6775: 
                   6776:   free_vector(xp,1,npar);
                   6777:   free_matrix(doldm,1,nlstate,1,npar);
                   6778:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6779: 
                   6780: }
                   6781: 
                   6782: /************ Variance of one-step probabilities  ******************/
                   6783: 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  6784:  {
                   6785:    int i, j=0,  k1, l1, tj;
                   6786:    int k2, l2, j1,  z1;
                   6787:    int k=0, l;
                   6788:    int first=1, first1, first2;
                   6789:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6790:    double **dnewm,**doldm;
                   6791:    double *xp;
                   6792:    double *gp, *gm;
                   6793:    double **gradg, **trgradg;
                   6794:    double **mu;
                   6795:    double age, cov[NCOVMAX+1];
                   6796:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6797:    int theta;
                   6798:    char fileresprob[FILENAMELENGTH];
                   6799:    char fileresprobcov[FILENAMELENGTH];
                   6800:    char fileresprobcor[FILENAMELENGTH];
                   6801:    double ***varpij;
                   6802: 
                   6803:    strcpy(fileresprob,"PROB_"); 
                   6804:    strcat(fileresprob,fileres);
                   6805:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6806:      printf("Problem with resultfile: %s\n", fileresprob);
                   6807:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6808:    }
                   6809:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6810:    strcat(fileresprobcov,fileresu);
                   6811:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6812:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6813:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6814:    }
                   6815:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6816:    strcat(fileresprobcor,fileresu);
                   6817:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6818:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6819:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6820:    }
                   6821:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6822:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6823:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6824:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6825:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6826:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6827:    pstamp(ficresprob);
                   6828:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6829:    fprintf(ficresprob,"# Age");
                   6830:    pstamp(ficresprobcov);
                   6831:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6832:    fprintf(ficresprobcov,"# Age");
                   6833:    pstamp(ficresprobcor);
                   6834:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6835:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6836: 
                   6837: 
1.222     brouard  6838:    for(i=1; i<=nlstate;i++)
                   6839:      for(j=1; j<=(nlstate+ndeath);j++){
                   6840:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6841:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6842:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6843:      }  
                   6844:    /* fprintf(ficresprob,"\n");
                   6845:       fprintf(ficresprobcov,"\n");
                   6846:       fprintf(ficresprobcor,"\n");
                   6847:    */
                   6848:    xp=vector(1,npar);
                   6849:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6850:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6851:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6852:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6853:    first=1;
                   6854:    fprintf(ficgp,"\n# Routine varprob");
                   6855:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6856:    fprintf(fichtm,"\n");
                   6857: 
1.288     brouard  6858:    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  6859:    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);
                   6860:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6861: and drawn. It helps understanding how is the covariance between two incidences.\
                   6862:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6863:    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  6864: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6865: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6866: standard deviations wide on each axis. <br>\
                   6867:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6868:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6869: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6870: 
1.222     brouard  6871:    cov[1]=1;
                   6872:    /* tj=cptcoveff; */
1.225     brouard  6873:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6874:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6875:    j1=0;
1.224     brouard  6876:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6877:      if  (cptcovn>0) {
                   6878:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6879:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6880:        fprintf(ficresprob, "**********\n#\n");
                   6881:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6882:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6883:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6884:                        
1.222     brouard  6885:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6886:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6887:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6888:                        
                   6889:                        
1.222     brouard  6890:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.319     brouard  6891:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]); */
                   6892:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtmcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6893:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6894:                        
1.222     brouard  6895:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6896:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6897:        fprintf(ficresprobcor, "**********\n#");    
                   6898:        if(invalidvarcomb[j1]){
                   6899:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6900:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6901:         continue;
                   6902:        }
                   6903:      }
                   6904:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6905:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6906:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6907:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6908:      for (age=bage; age<=fage; age ++){ 
                   6909:        cov[2]=age;
                   6910:        if(nagesqr==1)
                   6911:         cov[3]= age*age;
                   6912:        for (k=1; k<=cptcovn;k++) {
                   6913:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6914:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6915:                                                                    * 1  1 1 1 1
                   6916:                                                                    * 2  2 1 1 1
                   6917:                                                                    * 3  1 2 1 1
                   6918:                                                                    */
                   6919:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6920:        }
1.319     brouard  6921:        /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6922:        /* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] */
                   6923:        /*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6924:        for (k=1; k<=cptcovage;k++)
                   6925:         cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.222     brouard  6926:        for (k=1; k<=cptcovprod;k++)
                   6927:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6928:                        
                   6929:                        
1.222     brouard  6930:        for(theta=1; theta <=npar; theta++){
                   6931:         for(i=1; i<=npar; i++)
                   6932:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6933:                                
1.222     brouard  6934:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6935:                                
1.222     brouard  6936:         k=0;
                   6937:         for(i=1; i<= (nlstate); i++){
                   6938:           for(j=1; j<=(nlstate+ndeath);j++){
                   6939:             k=k+1;
                   6940:             gp[k]=pmmij[i][j];
                   6941:           }
                   6942:         }
1.220     brouard  6943:                                
1.222     brouard  6944:         for(i=1; i<=npar; i++)
                   6945:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6946:                                
1.222     brouard  6947:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6948:         k=0;
                   6949:         for(i=1; i<=(nlstate); i++){
                   6950:           for(j=1; j<=(nlstate+ndeath);j++){
                   6951:             k=k+1;
                   6952:             gm[k]=pmmij[i][j];
                   6953:           }
                   6954:         }
1.220     brouard  6955:                                
1.222     brouard  6956:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6957:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6958:        }
1.126     brouard  6959: 
1.222     brouard  6960:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6961:         for(theta=1; theta <=npar; theta++)
                   6962:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6963:                        
1.222     brouard  6964:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6965:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6966:                        
1.222     brouard  6967:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6968:                        
1.222     brouard  6969:        k=0;
                   6970:        for(i=1; i<=(nlstate); i++){
                   6971:         for(j=1; j<=(nlstate+ndeath);j++){
                   6972:           k=k+1;
                   6973:           mu[k][(int) age]=pmmij[i][j];
                   6974:         }
                   6975:        }
                   6976:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6977:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6978:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6979:                        
1.222     brouard  6980:        /*printf("\n%d ",(int)age);
                   6981:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6982:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6983:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6984:         }*/
1.220     brouard  6985:                        
1.222     brouard  6986:        fprintf(ficresprob,"\n%d ",(int)age);
                   6987:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6988:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6989:                        
1.222     brouard  6990:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6991:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6992:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6993:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6994:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6995:        }
                   6996:        i=0;
                   6997:        for (k=1; k<=(nlstate);k++){
                   6998:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6999:           i++;
                   7000:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7001:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7002:           for (j=1; j<=i;j++){
                   7003:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7004:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7005:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7006:           }
                   7007:         }
                   7008:        }/* end of loop for state */
                   7009:      } /* end of loop for age */
                   7010:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7011:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7012:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7013:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7014:     
                   7015:      /* Confidence intervalle of pij  */
                   7016:      /*
                   7017:        fprintf(ficgp,"\nunset parametric;unset label");
                   7018:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7019:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7020:        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);
                   7021:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7022:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7023:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7024:      */
                   7025:                
                   7026:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7027:      first1=1;first2=2;
                   7028:      for (k2=1; k2<=(nlstate);k2++){
                   7029:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7030:         if(l2==k2) continue;
                   7031:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7032:         for (k1=1; k1<=(nlstate);k1++){
                   7033:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7034:             if(l1==k1) continue;
                   7035:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7036:             if(i<=j) continue;
                   7037:             for (age=bage; age<=fage; age ++){ 
                   7038:               if ((int)age %5==0){
                   7039:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7040:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7041:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7042:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7043:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7044:                 c12=cv12/sqrt(v1*v2);
                   7045:                 /* Computing eigen value of matrix of covariance */
                   7046:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7047:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7048:                 if ((lc2 <0) || (lc1 <0) ){
                   7049:                   if(first2==1){
                   7050:                     first1=0;
                   7051:                     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);
                   7052:                   }
                   7053:                   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);
                   7054:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7055:                   /* lc2=fabs(lc2); */
                   7056:                 }
1.220     brouard  7057:                                                                
1.222     brouard  7058:                 /* Eigen vectors */
1.280     brouard  7059:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7060:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7061:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7062:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7063:                 }else
                   7064:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7065:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7066:                 v21=(lc1-v1)/cv12*v11;
                   7067:                 v12=-v21;
                   7068:                 v22=v11;
                   7069:                 tnalp=v21/v11;
                   7070:                 if(first1==1){
                   7071:                   first1=0;
                   7072:                   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);
                   7073:                 }
                   7074:                 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);
                   7075:                 /*printf(fignu*/
                   7076:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7077:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7078:                 if(first==1){
                   7079:                   first=0;
                   7080:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7081:                   fprintf(ficgp,"\nset parametric;unset label");
                   7082:                   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);
                   7083:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7084:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7085:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7086: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7087:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7088:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7089:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7090:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7091:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7092:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7093:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7094:                   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  7095:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7096:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7097:                 }else{
                   7098:                   first=0;
                   7099:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7100:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7101:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7102:                   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  7103:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7104:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7105:                 }/* if first */
                   7106:               } /* age mod 5 */
                   7107:             } /* end loop age */
                   7108:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7109:             first=1;
                   7110:           } /*l12 */
                   7111:         } /* k12 */
                   7112:        } /*l1 */
                   7113:      }/* k1 */
                   7114:    }  /* loop on combination of covariates j1 */
                   7115:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7116:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7117:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7118:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7119:    free_vector(xp,1,npar);
                   7120:    fclose(ficresprob);
                   7121:    fclose(ficresprobcov);
                   7122:    fclose(ficresprobcor);
                   7123:    fflush(ficgp);
                   7124:    fflush(fichtmcov);
                   7125:  }
1.126     brouard  7126: 
                   7127: 
                   7128: /******************* Printing html file ***********/
1.201     brouard  7129: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7130:                  int lastpass, int stepm, int weightopt, char model[],\
                   7131:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7132:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7133:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7134:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7135:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7136:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7137:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7138:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7139: </ul>");
1.319     brouard  7140: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7141: /* </ul>", model); */
1.214     brouard  7142:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7143:    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",
                   7144:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   7145:    fprintf(fichtm,"<li> - Observed 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  7146:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7147:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7148:    fprintf(fichtm,"\
                   7149:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7150:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7151:    fprintf(fichtm,"\
1.217     brouard  7152:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7153:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7154:    fprintf(fichtm,"\
1.288     brouard  7155:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7156:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7157:    fprintf(fichtm,"\
1.288     brouard  7158:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7159:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7160:    fprintf(fichtm,"\
1.211     brouard  7161:  - (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  7162:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7163:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7164:    if(prevfcast==1){
                   7165:      fprintf(fichtm,"\
                   7166:  - Prevalence projections by age and states:                           \
1.201     brouard  7167:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7168:    }
1.126     brouard  7169: 
                   7170: 
1.225     brouard  7171:    m=pow(2,cptcoveff);
1.222     brouard  7172:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7173: 
1.317     brouard  7174:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7175: 
                   7176:    jj1=0;
                   7177: 
                   7178:    fprintf(fichtm," \n<ul>");
                   7179:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7180:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7181:      if(m != 1 && TKresult[nres]!= k1)
                   7182:        continue;
                   7183:      jj1++;
                   7184:      if (cptcovn > 0) {
                   7185:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7186:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7187:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7188:        }
                   7189:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7190:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7191:        }
                   7192:        fprintf(fichtm,"\">");
                   7193:        
                   7194:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7195:        fprintf(fichtm,"************ Results for covariates");
                   7196:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7197:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7198:        }
                   7199:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7200:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7201:        }
                   7202:        if(invalidvarcomb[k1]){
                   7203:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7204:         continue;
                   7205:        }
                   7206:        fprintf(fichtm,"</a></li>");
                   7207:      } /* cptcovn >0 */
                   7208:    }
1.317     brouard  7209:    fprintf(fichtm," \n</ul>");
1.264     brouard  7210: 
1.222     brouard  7211:    jj1=0;
1.237     brouard  7212: 
                   7213:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7214:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7215:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7216:        continue;
1.220     brouard  7217: 
1.222     brouard  7218:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7219:      jj1++;
                   7220:      if (cptcovn > 0) {
1.264     brouard  7221:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7222:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7223:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7224:        }
                   7225:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7226:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7227:        }
                   7228:        fprintf(fichtm,"\"</a>");
                   7229:  
1.222     brouard  7230:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7231:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7232:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7233:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7234:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7235:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7236:        }
1.237     brouard  7237:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7238:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7239:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7240:       }
                   7241:        
1.230     brouard  7242:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321   ! brouard  7243:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7244:        if(invalidvarcomb[k1]){
                   7245:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7246:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7247:         continue;
                   7248:        }
                   7249:      }
                   7250:      /* aij, bij */
1.259     brouard  7251:      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  7252: <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  7253:      /* Pij */
1.241     brouard  7254:      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> \
                   7255: <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  7256:      /* Quasi-incidences */
                   7257:      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  7258:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7259:  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  7260: 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> \
                   7261: <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  7262:      /* Survival functions (period) in state j */
                   7263:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7264:        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> \
1.241     brouard  7265: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7266:      }
                   7267:      /* State specific survival functions (period) */
                   7268:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7269:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7270:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7271:  <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7272:      }
1.288     brouard  7273:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7274:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7275:        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> \
                   7276: <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7277:      }
1.296     brouard  7278:      if(prevbcast==1){
1.288     brouard  7279:        /* Backward prevalence in each health state */
1.222     brouard  7280:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7281:         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  7282: <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  7283:        }
1.217     brouard  7284:      }
1.222     brouard  7285:      if(prevfcast==1){
1.288     brouard  7286:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7287:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7288:         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);
                   7289:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7290:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7291:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7292:        }
                   7293:      }
1.296     brouard  7294:      if(prevbcast==1){
1.268     brouard  7295:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7296:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7297:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7298:  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 \
                   7299:  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  7300: 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);
                   7301:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7302:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7303:        }
                   7304:      }
1.220     brouard  7305:         
1.222     brouard  7306:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7307:        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);
                   7308:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7309:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7310:      }
                   7311:      /* } /\* end i1 *\/ */
                   7312:    }/* End k1 */
                   7313:    fprintf(fichtm,"</ul>");
1.126     brouard  7314: 
1.222     brouard  7315:    fprintf(fichtm,"\
1.126     brouard  7316: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7317:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7318:  - 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  7319: But because parameters are usually highly correlated (a higher incidence of disability \
                   7320: and a higher incidence of recovery can give very close observed transition) it might \
                   7321: be very useful to look not only at linear confidence intervals estimated from the \
                   7322: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7323: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7324: covariance matrix of the one-step probabilities. \
                   7325: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7326: 
1.222     brouard  7327:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7328:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7329:    fprintf(fichtm,"\
1.126     brouard  7330:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7331:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7332: 
1.222     brouard  7333:    fprintf(fichtm,"\
1.126     brouard  7334:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7335:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7336:    fprintf(fichtm,"\
1.126     brouard  7337:  - 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): \
                   7338:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7339:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7340:    fprintf(fichtm,"\
1.126     brouard  7341:  - (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): \
                   7342:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7343:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7344:    fprintf(fichtm,"\
1.288     brouard  7345:  - 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  7346:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7347:    fprintf(fichtm,"\
1.128     brouard  7348:  - 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  7349:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7350:    fprintf(fichtm,"\
1.288     brouard  7351:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7352:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7353: 
                   7354: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7355: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7356: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7357: /*     <br>",fileres,fileres,fileres,fileres); */
                   7358: /*  else  */
                   7359: /*    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  7360:    fflush(fichtm);
1.126     brouard  7361: 
1.225     brouard  7362:    m=pow(2,cptcoveff);
1.222     brouard  7363:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7364: 
1.317     brouard  7365:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7366: 
                   7367:   jj1=0;
                   7368: 
                   7369:    fprintf(fichtm," \n<ul>");
                   7370:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7371:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7372:      if(m != 1 && TKresult[nres]!= k1)
                   7373:        continue;
                   7374:      jj1++;
                   7375:      if (cptcovn > 0) {
                   7376:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7377:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7378:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7379:        }
                   7380:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7381:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7382:        }
                   7383:        fprintf(fichtm,"\">");
                   7384:        
                   7385:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7386:        fprintf(fichtm,"************ Results for covariates");
                   7387:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7388:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7389:        }
                   7390:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7391:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7392:        }
                   7393:        if(invalidvarcomb[k1]){
                   7394:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7395:         continue;
                   7396:        }
                   7397:        fprintf(fichtm,"</a></li>");
                   7398:      } /* cptcovn >0 */
                   7399:    }
                   7400:    fprintf(fichtm," \n</ul>");
                   7401: 
1.222     brouard  7402:    jj1=0;
1.237     brouard  7403: 
1.241     brouard  7404:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7405:    for(k1=1; k1<=m;k1++){
1.253     brouard  7406:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7407:        continue;
1.222     brouard  7408:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7409:      jj1++;
1.126     brouard  7410:      if (cptcovn > 0) {
1.317     brouard  7411:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7412:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7413:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7414:        }
                   7415:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7416:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7417:        }
                   7418:        fprintf(fichtm,"\"</a>");
                   7419:        
1.126     brouard  7420:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7421:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7422:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7423:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7424:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7425:        }
1.237     brouard  7426:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7427:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7428:       }
                   7429: 
1.321   ! brouard  7430:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7431: 
1.222     brouard  7432:        if(invalidvarcomb[k1]){
                   7433:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7434:         continue;
                   7435:        }
1.126     brouard  7436:      }
                   7437:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7438:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7439: 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);
                   7440:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7441:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7442:      }
                   7443:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7444: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7445: true period expectancies (those weighted with period prevalences are also\
                   7446:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7447:  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);
                   7448:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7449:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7450:      /* } /\* end i1 *\/ */
                   7451:    }/* End k1 */
1.241     brouard  7452:   }/* End nres */
1.222     brouard  7453:    fprintf(fichtm,"</ul>");
                   7454:    fflush(fichtm);
1.126     brouard  7455: }
                   7456: 
                   7457: /******************* Gnuplot file **************/
1.296     brouard  7458: 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  7459: 
                   7460:   char dirfileres[132],optfileres[132];
1.264     brouard  7461:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7462:   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  7463:   int lv=0, vlv=0, kl=0;
1.130     brouard  7464:   int ng=0;
1.201     brouard  7465:   int vpopbased;
1.223     brouard  7466:   int ioffset; /* variable offset for columns */
1.270     brouard  7467:   int iyearc=1; /* variable column for year of projection  */
                   7468:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7469:   int nres=0; /* Index of resultline */
1.266     brouard  7470:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7471: 
1.126     brouard  7472: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7473: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7474: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7475: /*   } */
                   7476: 
                   7477:   /*#ifdef windows */
                   7478:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7479:   /*#endif */
1.225     brouard  7480:   m=pow(2,cptcoveff);
1.126     brouard  7481: 
1.274     brouard  7482:   /* diagram of the model */
                   7483:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7484:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7485:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7486:   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);
                   7487: 
                   7488:   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);
                   7489:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7490:   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);
                   7491:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7492:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7493:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7494:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7495: 
1.202     brouard  7496:   /* Contribution to likelihood */
                   7497:   /* Plot the probability implied in the likelihood */
1.223     brouard  7498:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7499:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7500:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7501:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7502: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7503:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7504: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7505:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7506:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7507:   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));
                   7508:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7509:   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));
                   7510:   for (i=1; i<= nlstate ; i ++) {
                   7511:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7512:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7513:     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);
                   7514:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7515:       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);
                   7516:     }
                   7517:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7518:   }
                   7519:   /* 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 */               
                   7520:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7521:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7522:   fprintf(ficgp,"\nset out;unset log\n");
                   7523:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7524: 
1.126     brouard  7525:   strcpy(dirfileres,optionfilefiname);
                   7526:   strcpy(optfileres,"vpl");
1.223     brouard  7527:   /* 1eme*/
1.238     brouard  7528:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7529:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7530:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7531:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7532:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7533:          continue;
                   7534:        /* We are interested in selected combination by the resultline */
1.246     brouard  7535:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7536:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7537:        strcpy(gplotlabel,"(");
1.238     brouard  7538:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7539:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7540:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7541:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7542:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7543:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7544:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7545:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7546:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7547:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7548:        }
                   7549:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7550:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7551:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7552:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7553:        }
                   7554:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7555:        /* printf("\n#\n"); */
1.238     brouard  7556:        fprintf(ficgp,"\n#\n");
                   7557:        if(invalidvarcomb[k1]){
1.260     brouard  7558:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7559:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7560:          continue;
                   7561:        }
1.235     brouard  7562:       
1.241     brouard  7563:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7564:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7565:        /* 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  7566:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7567:        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);
                   7568:        /* 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); */
                   7569:       /* k1-1 error should be nres-1*/
1.238     brouard  7570:        for (i=1; i<= nlstate ; i ++) {
                   7571:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7572:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7573:        }
1.288     brouard  7574:        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  7575:        for (i=1; i<= nlstate ; i ++) {
                   7576:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7577:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7578:        } 
1.260     brouard  7579:        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  7580:        for (i=1; i<= nlstate ; i ++) {
                   7581:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7582:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7583:        }  
1.265     brouard  7584:        /* 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)); */
                   7585:        
                   7586:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7587:         if(cptcoveff ==0){
1.271     brouard  7588:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7589:        }else{
                   7590:          kl=0;
                   7591:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7592:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7593:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7594:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7595:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7596:            vlv= nbcode[Tvaraff[k]][lv];
                   7597:            kl++;
                   7598:            /* 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 *\/ */
                   7599:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7600:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7601:            /* ''  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*/
                   7602:            if(k==cptcoveff){
                   7603:              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], \
                   7604:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7605:            }else{
                   7606:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7607:              kl++;
                   7608:            }
                   7609:          } /* end covariate */
                   7610:        } /* end if no covariate */
                   7611: 
1.296     brouard  7612:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7613:          /* 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  7614:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7615:          if(cptcoveff ==0){
1.245     brouard  7616:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7617:          }else{
                   7618:            kl=0;
                   7619:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7620:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7621:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7622:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7623:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7624:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7625:              kl++;
1.238     brouard  7626:              /* 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 *\/ */
                   7627:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7628:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7629:              /* ''  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*/
                   7630:              if(k==cptcoveff){
1.245     brouard  7631:                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  7632:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7633:              }else{
                   7634:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7635:                kl++;
                   7636:              }
                   7637:            } /* end covariate */
                   7638:          } /* end if no covariate */
1.296     brouard  7639:          if(prevbcast == 1){
1.268     brouard  7640:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7641:            /* k1-1 error should be nres-1*/
                   7642:            for (i=1; i<= nlstate ; i ++) {
                   7643:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7644:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7645:            }
1.271     brouard  7646:            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  7647:            for (i=1; i<= nlstate ; i ++) {
                   7648:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7649:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7650:            } 
1.276     brouard  7651:            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  7652:            for (i=1; i<= nlstate ; i ++) {
                   7653:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7654:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7655:            } 
1.274     brouard  7656:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7657:          } /* end if backprojcast */
1.296     brouard  7658:        } /* end if prevbcast */
1.276     brouard  7659:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7660:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7661:       } /* nres */
1.201     brouard  7662:     } /* k1 */
                   7663:   } /* cpt */
1.235     brouard  7664: 
                   7665:   
1.126     brouard  7666:   /*2 eme*/
1.238     brouard  7667:   for (k1=1; k1<= m ; k1 ++){  
                   7668:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7669:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7670:        continue;
                   7671:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7672:       strcpy(gplotlabel,"(");
1.238     brouard  7673:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7674:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7675:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7676:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7677:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7678:        vlv= nbcode[Tvaraff[k]][lv];
                   7679:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7680:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7681:       }
1.237     brouard  7682:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7683:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7684:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7685:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7686:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7687:       }
1.264     brouard  7688:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7689:       fprintf(ficgp,"\n#\n");
1.223     brouard  7690:       if(invalidvarcomb[k1]){
                   7691:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7692:        continue;
                   7693:       }
1.219     brouard  7694:                        
1.241     brouard  7695:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7696:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7697:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7698:        if(vpopbased==0){
1.238     brouard  7699:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7700:        }else
1.238     brouard  7701:          fprintf(ficgp,"\nreplot ");
                   7702:        for (i=1; i<= nlstate+1 ; i ++) {
                   7703:          k=2*i;
1.261     brouard  7704:          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  7705:          for (j=1; j<= nlstate+1 ; j ++) {
                   7706:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7707:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7708:          }   
                   7709:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7710:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7711:          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  7712:          for (j=1; j<= nlstate+1 ; j ++) {
                   7713:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7714:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7715:          }   
                   7716:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7717:          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  7718:          for (j=1; j<= nlstate+1 ; j ++) {
                   7719:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7720:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7721:          }   
                   7722:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7723:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7724:        } /* state */
                   7725:       } /* vpopbased */
1.264     brouard  7726:       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  7727:     } /* end nres */
                   7728:   } /* k1 end 2 eme*/
                   7729:        
                   7730:        
                   7731:   /*3eme*/
                   7732:   for (k1=1; k1<= m ; k1 ++){
                   7733:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7734:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7735:        continue;
                   7736: 
                   7737:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7738:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7739:        strcpy(gplotlabel,"(");
1.238     brouard  7740:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7741:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7742:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7743:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7744:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7745:          vlv= nbcode[Tvaraff[k]][lv];
                   7746:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7747:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7748:        }
                   7749:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7750:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7751:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7752:        }       
1.264     brouard  7753:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7754:        fprintf(ficgp,"\n#\n");
                   7755:        if(invalidvarcomb[k1]){
                   7756:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7757:          continue;
                   7758:        }
                   7759:                        
                   7760:        /*       k=2+nlstate*(2*cpt-2); */
                   7761:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7762:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7763:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7764:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7765: 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  7766:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7767:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7768:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7769:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7770:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7771:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7772:                                
1.238     brouard  7773:        */
                   7774:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7775:          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  7776:          /*    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  7777:                                
1.238     brouard  7778:        } 
1.261     brouard  7779:        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  7780:       }
1.264     brouard  7781:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7782:     } /* end nres */
                   7783:   } /* end kl 3eme */
1.126     brouard  7784:   
1.223     brouard  7785:   /* 4eme */
1.201     brouard  7786:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7787:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7788:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7789:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7790:        continue;
1.238     brouard  7791:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7792:        strcpy(gplotlabel,"(");
1.238     brouard  7793:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7794:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7795:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7796:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7797:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7798:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7799:          vlv= nbcode[Tvaraff[k]][lv];
                   7800:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7801:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7802:        }
                   7803:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7804:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7805:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7806:        }       
1.264     brouard  7807:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7808:        fprintf(ficgp,"\n#\n");
                   7809:        if(invalidvarcomb[k1]){
                   7810:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7811:          continue;
1.223     brouard  7812:        }
1.238     brouard  7813:       
1.241     brouard  7814:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7815:        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  7816:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7817: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7818:        k=3;
                   7819:        for (i=1; i<= nlstate ; i ++){
                   7820:          if(i==1){
                   7821:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7822:          }else{
                   7823:            fprintf(ficgp,", '' ");
                   7824:          }
                   7825:          l=(nlstate+ndeath)*(i-1)+1;
                   7826:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7827:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7828:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7829:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7830:        } /* nlstate */
1.264     brouard  7831:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7832:       } /* end cpt state*/ 
                   7833:     } /* end nres */
                   7834:   } /* end covariate k1 */  
                   7835: 
1.220     brouard  7836: /* 5eme */
1.201     brouard  7837:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7838:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7839:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7840:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7841:        continue;
1.238     brouard  7842:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7843:        strcpy(gplotlabel,"(");
1.238     brouard  7844:        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);
                   7845:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7846:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7847:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7848:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7849:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7850:          vlv= nbcode[Tvaraff[k]][lv];
                   7851:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7852:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7853:        }
                   7854:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7855:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7856:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7857:        }       
1.264     brouard  7858:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7859:        fprintf(ficgp,"\n#\n");
                   7860:        if(invalidvarcomb[k1]){
                   7861:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7862:          continue;
                   7863:        }
1.227     brouard  7864:       
1.241     brouard  7865:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7866:        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  7867:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7868: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7869:        k=3;
                   7870:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7871:          if(j==1)
                   7872:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7873:          else
                   7874:            fprintf(ficgp,", '' ");
                   7875:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7876:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7877:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7878:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7879:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7880:        } /* nlstate */
                   7881:        fprintf(ficgp,", '' ");
                   7882:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7883:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7884:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7885:          if(j < nlstate)
                   7886:            fprintf(ficgp,"$%d +",k+l);
                   7887:          else
                   7888:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7889:        }
1.264     brouard  7890:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7891:       } /* end cpt state*/ 
                   7892:     } /* end covariate */  
                   7893:   } /* end nres */
1.227     brouard  7894:   
1.220     brouard  7895: /* 6eme */
1.202     brouard  7896:   /* CV preval stable (period) for each covariate */
1.237     brouard  7897:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7898:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7899:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7900:       continue;
1.255     brouard  7901:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7902:       strcpy(gplotlabel,"(");      
1.288     brouard  7903:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7904:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7905:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7906:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7907:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7908:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7909:        vlv= nbcode[Tvaraff[k]][lv];
                   7910:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7911:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7912:       }
1.237     brouard  7913:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7914:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7915:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7916:       }        
1.264     brouard  7917:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7918:       fprintf(ficgp,"\n#\n");
1.223     brouard  7919:       if(invalidvarcomb[k1]){
1.227     brouard  7920:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7921:        continue;
1.223     brouard  7922:       }
1.227     brouard  7923:       
1.241     brouard  7924:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7925:       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  7926:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7927: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7928:       k=3; /* Offset */
1.255     brouard  7929:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7930:        if(i==1)
                   7931:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7932:        else
                   7933:          fprintf(ficgp,", '' ");
1.255     brouard  7934:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7935:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7936:        for (j=2; j<= nlstate ; j ++)
                   7937:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7938:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7939:       } /* nlstate */
1.264     brouard  7940:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7941:     } /* end cpt state*/ 
                   7942:   } /* end covariate */  
1.227     brouard  7943:   
                   7944:   
1.220     brouard  7945: /* 7eme */
1.296     brouard  7946:   if(prevbcast == 1){
1.288     brouard  7947:     /* CV backward prevalence  for each covariate */
1.237     brouard  7948:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7949:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7950:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7951:        continue;
1.268     brouard  7952:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7953:        strcpy(gplotlabel,"(");      
1.288     brouard  7954:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7955:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7956:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7957:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7958:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7959:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7960:          vlv= nbcode[Tvaraff[k]][lv];
                   7961:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7962:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7963:        }
1.237     brouard  7964:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7965:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7966:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7967:        }       
1.264     brouard  7968:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7969:        fprintf(ficgp,"\n#\n");
                   7970:        if(invalidvarcomb[k1]){
                   7971:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7972:          continue;
                   7973:        }
                   7974:        
1.241     brouard  7975:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7976:        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  7977:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7978: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7979:        k=3; /* Offset */
1.268     brouard  7980:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7981:          if(i==1)
                   7982:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7983:          else
                   7984:            fprintf(ficgp,", '' ");
                   7985:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7986:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7987:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7988:          /* 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  7989:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7990:          /* for (j=2; j<= nlstate ; j ++) */
                   7991:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7992:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7993:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7994:        } /* nlstate */
1.264     brouard  7995:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7996:       } /* end cpt state*/ 
                   7997:     } /* end covariate */  
1.296     brouard  7998:   } /* End if prevbcast */
1.218     brouard  7999:   
1.223     brouard  8000:   /* 8eme */
1.218     brouard  8001:   if(prevfcast==1){
1.288     brouard  8002:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8003:     
1.237     brouard  8004:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8005:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8006:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8007:        continue;
1.211     brouard  8008:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8009:        strcpy(gplotlabel,"(");      
1.288     brouard  8010:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8011:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8012:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8013:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8014:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8015:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8016:          vlv= nbcode[Tvaraff[k]][lv];
                   8017:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8018:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8019:        }
1.237     brouard  8020:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8021:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8022:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8023:        }       
1.264     brouard  8024:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8025:        fprintf(ficgp,"\n#\n");
                   8026:        if(invalidvarcomb[k1]){
                   8027:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8028:          continue;
                   8029:        }
                   8030:        
                   8031:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8032:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8033:        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  8034:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8035: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8036: 
                   8037:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8038:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8039:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8040:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8041:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8042:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8043:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8044:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8045:          if(i==istart){
1.227     brouard  8046:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8047:          }else{
                   8048:            fprintf(ficgp,",\\\n '' ");
                   8049:          }
                   8050:          if(cptcoveff ==0){ /* No covariate */
                   8051:            ioffset=2; /* Age is in 2 */
                   8052:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8053:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8054:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8055:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8056:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8057:            if(i==nlstate+1){
1.270     brouard  8058:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8059:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8060:              fprintf(ficgp,",\\\n '' ");
                   8061:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8062:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8063:                     offyear,                           \
1.268     brouard  8064:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8065:            }else
1.227     brouard  8066:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8067:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8068:          }else{ /* more than 2 covariates */
1.270     brouard  8069:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8070:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8071:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8072:            iyearc=ioffset-1;
                   8073:            iagec=ioffset;
1.227     brouard  8074:            fprintf(ficgp," u %d:(",ioffset); 
                   8075:            kl=0;
                   8076:            strcpy(gplotcondition,"(");
                   8077:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8078:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8079:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8080:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8081:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8082:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8083:              kl++;
                   8084:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8085:              kl++;
                   8086:              if(k <cptcoveff && cptcoveff>1)
                   8087:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8088:            }
                   8089:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8090:            /* 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 *\/ */
                   8091:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8092:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8093:            /* ''  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*/
                   8094:            if(i==nlstate+1){
1.270     brouard  8095:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8096:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8097:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8098:              fprintf(ficgp," u %d:(",iagec); 
                   8099:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8100:                      iyearc, iagec, offyear,                           \
                   8101:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8102: /*  '' 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  8103:            }else{
                   8104:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8105:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8106:            }
                   8107:          } /* end if covariate */
                   8108:        } /* nlstate */
1.264     brouard  8109:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8110:       } /* end cpt state*/
                   8111:     } /* end covariate */
                   8112:   } /* End if prevfcast */
1.227     brouard  8113:   
1.296     brouard  8114:   if(prevbcast==1){
1.268     brouard  8115:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8116:     
                   8117:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8118:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8119:       if(m != 1 && TKresult[nres]!= k1)
                   8120:        continue;
                   8121:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8122:        strcpy(gplotlabel,"(");      
                   8123:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8124:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8125:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8126:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8127:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8128:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8129:          vlv= nbcode[Tvaraff[k]][lv];
                   8130:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8131:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8132:        }
                   8133:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8134:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8135:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8136:        }       
                   8137:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8138:        fprintf(ficgp,"\n#\n");
                   8139:        if(invalidvarcomb[k1]){
                   8140:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8141:          continue;
                   8142:        }
                   8143:        
                   8144:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8145:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8146:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8147:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8148: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8149: 
                   8150:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8151:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8152:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8153:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8154:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8155:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8156:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8157:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8158:          if(i==istart){
                   8159:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8160:          }else{
                   8161:            fprintf(ficgp,",\\\n '' ");
                   8162:          }
                   8163:          if(cptcoveff ==0){ /* No covariate */
                   8164:            ioffset=2; /* Age is in 2 */
                   8165:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8166:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8167:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8168:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8169:            fprintf(ficgp," u %d:(", ioffset); 
                   8170:            if(i==nlstate+1){
1.270     brouard  8171:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8172:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8173:              fprintf(ficgp,",\\\n '' ");
                   8174:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8175:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8176:                     offbyear,                          \
                   8177:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8178:            }else
                   8179:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8180:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8181:          }else{ /* more than 2 covariates */
1.270     brouard  8182:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8183:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8184:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8185:            iyearc=ioffset-1;
                   8186:            iagec=ioffset;
1.268     brouard  8187:            fprintf(ficgp," u %d:(",ioffset); 
                   8188:            kl=0;
                   8189:            strcpy(gplotcondition,"(");
                   8190:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8191:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8192:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8193:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8194:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8195:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8196:              kl++;
                   8197:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8198:              kl++;
                   8199:              if(k <cptcoveff && cptcoveff>1)
                   8200:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8201:            }
                   8202:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8203:            /* 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 *\/ */
                   8204:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8205:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8206:            /* ''  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*/
                   8207:            if(i==nlstate+1){
1.270     brouard  8208:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8209:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8210:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8211:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8212:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8213:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8214:                      iyearc,iagec,offbyear,                            \
                   8215:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8216: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8217:            }else{
                   8218:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8219:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8220:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8221:            }
                   8222:          } /* end if covariate */
                   8223:        } /* nlstate */
                   8224:        fprintf(ficgp,"\nset out; unset label;\n");
                   8225:       } /* end cpt state*/
                   8226:     } /* end covariate */
1.296     brouard  8227:   } /* End if prevbcast */
1.268     brouard  8228:   
1.227     brouard  8229:   
1.238     brouard  8230:   /* 9eme writing MLE parameters */
                   8231:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8232:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8233:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8234:     for(k=1; k <=(nlstate+ndeath); k++){
                   8235:       if (k != i) {
1.227     brouard  8236:        fprintf(ficgp,"#   current state %d\n",k);
                   8237:        for(j=1; j <=ncovmodel; j++){
                   8238:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8239:          jk++; 
                   8240:        }
                   8241:        fprintf(ficgp,"\n");
1.126     brouard  8242:       }
                   8243:     }
1.223     brouard  8244:   }
1.187     brouard  8245:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8246:   
1.145     brouard  8247:   /*goto avoid;*/
1.238     brouard  8248:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8249:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8250:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8251:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8252:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8253:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8254:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8255:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8256:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8257:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8258:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8259:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8260:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8261:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8262:   fprintf(ficgp,"#\n");
1.223     brouard  8263:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8264:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8265:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8266:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8267:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8268:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8269:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8270:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8271:        continue;
1.264     brouard  8272:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8273:       strcpy(gplotlabel,"(");
1.276     brouard  8274:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8275:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8276:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8277:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8278:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8279:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8280:        vlv= nbcode[Tvaraff[k]][lv];
                   8281:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8282:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8283:       }
1.237     brouard  8284:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8285:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8286:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8287:       }        
1.264     brouard  8288:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8289:       fprintf(ficgp,"\n#\n");
1.264     brouard  8290:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8291:       fprintf(ficgp,"\nset key outside ");
                   8292:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8293:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8294:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8295:       if (ng==1){
                   8296:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8297:        fprintf(ficgp,"\nunset log y");
                   8298:       }else if (ng==2){
                   8299:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8300:        fprintf(ficgp,"\nset log y");
                   8301:       }else if (ng==3){
                   8302:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8303:        fprintf(ficgp,"\nset log y");
                   8304:       }else
                   8305:        fprintf(ficgp,"\nunset title ");
                   8306:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8307:       i=1;
                   8308:       for(k2=1; k2<=nlstate; k2++) {
                   8309:        k3=i;
                   8310:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8311:          if (k != k2){
                   8312:            switch( ng) {
                   8313:            case 1:
                   8314:              if(nagesqr==0)
                   8315:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8316:              else /* nagesqr =1 */
                   8317:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8318:              break;
                   8319:            case 2: /* ng=2 */
                   8320:              if(nagesqr==0)
                   8321:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8322:              else /* nagesqr =1 */
                   8323:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8324:              break;
                   8325:            case 3:
                   8326:              if(nagesqr==0)
                   8327:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8328:              else /* nagesqr =1 */
                   8329:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8330:              break;
                   8331:            }
                   8332:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8333:            ijp=1; /* product no age */
                   8334:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8335:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8336:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8337:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8338:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8339:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8340:                    if(DummyV[j]==0){
                   8341:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8342:                    }else{ /* quantitative */
                   8343:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8344:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8345:                    }
                   8346:                    ij++;
1.237     brouard  8347:                  }
1.268     brouard  8348:                } 
                   8349:              }else if(cptcovprod >0){
                   8350:                if(j==Tprod[ijp]) { /* */ 
                   8351:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8352:                  if(ijp <=cptcovprod) { /* Product */
                   8353:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8354:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8355:                        /* 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)]); */
                   8356:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8357:                      }else{ /* Vn is dummy and Vm is quanti */
                   8358:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8359:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8360:                      }
                   8361:                    }else{ /* Vn*Vm Vn is quanti */
                   8362:                      if(DummyV[Tvard[ijp][2]]==0){
                   8363:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8364:                      }else{ /* Both quanti */
                   8365:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8366:                      }
1.237     brouard  8367:                    }
1.268     brouard  8368:                    ijp++;
1.237     brouard  8369:                  }
1.268     brouard  8370:                } /* end Tprod */
1.237     brouard  8371:              } else{  /* simple covariate */
1.264     brouard  8372:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8373:                if(Dummy[j]==0){
                   8374:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8375:                }else{ /* quantitative */
                   8376:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8377:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8378:                }
1.237     brouard  8379:              } /* end simple */
                   8380:            } /* end j */
1.223     brouard  8381:          }else{
                   8382:            i=i-ncovmodel;
                   8383:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8384:              fprintf(ficgp," (1.");
                   8385:          }
1.227     brouard  8386:          
1.223     brouard  8387:          if(ng != 1){
                   8388:            fprintf(ficgp,")/(1");
1.227     brouard  8389:            
1.264     brouard  8390:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8391:              if(nagesqr==0)
1.264     brouard  8392:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8393:              else /* nagesqr =1 */
1.264     brouard  8394:                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  8395:               
1.223     brouard  8396:              ij=1;
                   8397:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8398:                 if(cptcovage >0){ 
                   8399:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8400:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8401:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8402:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8403:                       ij++;
                   8404:                     }
                   8405:                   }
                   8406:                 }else
                   8407:                   fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/* Valgrind bug nbcode */
1.223     brouard  8408:              }
                   8409:              fprintf(ficgp,")");
                   8410:            }
                   8411:            fprintf(ficgp,")");
                   8412:            if(ng ==2)
1.276     brouard  8413:              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  8414:            else /* ng= 3 */
1.276     brouard  8415:              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.223     brouard  8416:          }else{ /* end ng <> 1 */
                   8417:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8418:              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  8419:          }
                   8420:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8421:            fprintf(ficgp,",");
                   8422:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8423:            fprintf(ficgp,",");
                   8424:          i=i+ncovmodel;
                   8425:        } /* end k */
                   8426:       } /* end k2 */
1.276     brouard  8427:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8428:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8429:     } /* end k1 */
1.223     brouard  8430:   } /* end ng */
                   8431:   /* avoid: */
                   8432:   fflush(ficgp); 
1.126     brouard  8433: }  /* end gnuplot */
                   8434: 
                   8435: 
                   8436: /*************** Moving average **************/
1.219     brouard  8437: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8438:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8439:    
1.222     brouard  8440:    int i, cpt, cptcod;
                   8441:    int modcovmax =1;
                   8442:    int mobilavrange, mob;
                   8443:    int iage=0;
1.288     brouard  8444:    int firstA1=0, firstA2=0;
1.222     brouard  8445: 
1.266     brouard  8446:    double sum=0., sumr=0.;
1.222     brouard  8447:    double age;
1.266     brouard  8448:    double *sumnewp, *sumnewm, *sumnewmr;
                   8449:    double *agemingood, *agemaxgood; 
                   8450:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8451:   
                   8452:   
1.278     brouard  8453:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8454:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8455: 
                   8456:    sumnewp = vector(1,ncovcombmax);
                   8457:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8458:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8459:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8460:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8461:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8462:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8463: 
                   8464:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8465:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8466:      sumnewp[cptcod]=0.;
1.266     brouard  8467:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8468:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8469:    }
                   8470:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8471:   
1.266     brouard  8472:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8473:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8474:      else mobilavrange=mobilav;
                   8475:      for (age=bage; age<=fage; age++)
                   8476:        for (i=1; i<=nlstate;i++)
                   8477:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8478:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8479:      /* We keep the original values on the extreme ages bage, fage and for 
                   8480:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8481:        we use a 5 terms etc. until the borders are no more concerned. 
                   8482:      */ 
                   8483:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8484:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8485:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8486:           sumnewm[cptcod]=0.;
                   8487:           for (i=1; i<=nlstate;i++){
1.222     brouard  8488:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8489:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8490:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8491:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8492:             }
                   8493:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8494:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8495:           } /* end i */
                   8496:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8497:         } /* end cptcod */
1.222     brouard  8498:        }/* end age */
                   8499:      }/* end mob */
1.266     brouard  8500:    }else{
                   8501:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8502:      return -1;
1.266     brouard  8503:    }
                   8504: 
                   8505:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8506:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8507:      if(invalidvarcomb[cptcod]){
                   8508:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8509:        continue;
                   8510:      }
1.219     brouard  8511: 
1.266     brouard  8512:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8513:        sumnewm[cptcod]=0.;
                   8514:        sumnewmr[cptcod]=0.;
                   8515:        for (i=1; i<=nlstate;i++){
                   8516:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8517:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8518:        }
                   8519:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8520:         agemingoodr[cptcod]=age;
                   8521:        }
                   8522:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8523:           agemingood[cptcod]=age;
                   8524:        }
                   8525:      } /* age */
                   8526:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8527:        sumnewm[cptcod]=0.;
1.266     brouard  8528:        sumnewmr[cptcod]=0.;
1.222     brouard  8529:        for (i=1; i<=nlstate;i++){
                   8530:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8531:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8532:        }
                   8533:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8534:         agemaxgoodr[cptcod]=age;
1.222     brouard  8535:        }
                   8536:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8537:         agemaxgood[cptcod]=age;
                   8538:        }
                   8539:      } /* age */
                   8540:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8541:      /* but they will change */
1.288     brouard  8542:      firstA1=0;firstA2=0;
1.266     brouard  8543:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8544:        sumnewm[cptcod]=0.;
                   8545:        sumnewmr[cptcod]=0.;
                   8546:        for (i=1; i<=nlstate;i++){
                   8547:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8548:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8549:        }
                   8550:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8551:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8552:           agemaxgoodr[cptcod]=age;  /* age min */
                   8553:           for (i=1; i<=nlstate;i++)
                   8554:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8555:         }else{ /* bad we change the value with the values of good ages */
                   8556:           for (i=1; i<=nlstate;i++){
                   8557:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8558:           } /* i */
                   8559:         } /* end bad */
                   8560:        }else{
                   8561:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8562:           agemaxgood[cptcod]=age;
                   8563:         }else{ /* bad we change the value with the values of good ages */
                   8564:           for (i=1; i<=nlstate;i++){
                   8565:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8566:           } /* i */
                   8567:         } /* end bad */
                   8568:        }/* end else */
                   8569:        sum=0.;sumr=0.;
                   8570:        for (i=1; i<=nlstate;i++){
                   8571:         sum+=mobaverage[(int)age][i][cptcod];
                   8572:         sumr+=probs[(int)age][i][cptcod];
                   8573:        }
                   8574:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8575:         if(!firstA1){
                   8576:           firstA1=1;
                   8577:           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);
                   8578:         }
                   8579:         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  8580:        } /* end bad */
                   8581:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8582:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8583:         if(!firstA2){
                   8584:           firstA2=1;
                   8585:           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);
                   8586:         }
                   8587:         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  8588:        } /* end bad */
                   8589:      }/* age */
1.266     brouard  8590: 
                   8591:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8592:        sumnewm[cptcod]=0.;
1.266     brouard  8593:        sumnewmr[cptcod]=0.;
1.222     brouard  8594:        for (i=1; i<=nlstate;i++){
                   8595:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8596:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8597:        } 
                   8598:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8599:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8600:           agemingoodr[cptcod]=age;
                   8601:           for (i=1; i<=nlstate;i++)
                   8602:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8603:         }else{ /* bad we change the value with the values of good ages */
                   8604:           for (i=1; i<=nlstate;i++){
                   8605:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8606:           } /* i */
                   8607:         } /* end bad */
                   8608:        }else{
                   8609:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8610:           agemingood[cptcod]=age;
                   8611:         }else{ /* bad */
                   8612:           for (i=1; i<=nlstate;i++){
                   8613:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8614:           } /* i */
                   8615:         } /* end bad */
                   8616:        }/* end else */
                   8617:        sum=0.;sumr=0.;
                   8618:        for (i=1; i<=nlstate;i++){
                   8619:         sum+=mobaverage[(int)age][i][cptcod];
                   8620:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8621:        }
1.266     brouard  8622:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8623:         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  8624:        } /* end bad */
                   8625:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8626:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8627:         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  8628:        } /* end bad */
                   8629:      }/* age */
1.266     brouard  8630: 
1.222     brouard  8631:                
                   8632:      for (age=bage; age<=fage; age++){
1.235     brouard  8633:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8634:        sumnewp[cptcod]=0.;
                   8635:        sumnewm[cptcod]=0.;
                   8636:        for (i=1; i<=nlstate;i++){
                   8637:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8638:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8639:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8640:        }
                   8641:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8642:      }
                   8643:      /* printf("\n"); */
                   8644:      /* } */
1.266     brouard  8645: 
1.222     brouard  8646:      /* brutal averaging */
1.266     brouard  8647:      /* for (i=1; i<=nlstate;i++){ */
                   8648:      /*   for (age=1; age<=bage; age++){ */
                   8649:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8650:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8651:      /*   }     */
                   8652:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8653:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8654:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8655:      /*   } */
                   8656:      /* } /\* end i status *\/ */
                   8657:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8658:      /*   for (age=1; age<=AGESUP; age++){ */
                   8659:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8660:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8661:      /*   } */
                   8662:      /* } */
1.222     brouard  8663:    }/* end cptcod */
1.266     brouard  8664:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8665:    free_vector(agemaxgood,1, ncovcombmax);
                   8666:    free_vector(agemingood,1, ncovcombmax);
                   8667:    free_vector(agemingoodr,1, ncovcombmax);
                   8668:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8669:    free_vector(sumnewm,1, ncovcombmax);
                   8670:    free_vector(sumnewp,1, ncovcombmax);
                   8671:    return 0;
                   8672:  }/* End movingaverage */
1.218     brouard  8673:  
1.126     brouard  8674: 
1.296     brouard  8675:  
1.126     brouard  8676: /************** Forecasting ******************/
1.296     brouard  8677: /* 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)*/
                   8678: 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){
                   8679:   /* dateintemean, mean date of interviews
                   8680:      dateprojd, year, month, day of starting projection 
                   8681:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8682:      agemin, agemax range of age
                   8683:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8684:   */
1.296     brouard  8685:   /* double anprojd, mprojd, jprojd; */
                   8686:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8687:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8688:   double agec; /* generic age */
1.296     brouard  8689:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8690:   double *popeffectif,*popcount;
                   8691:   double ***p3mat;
1.218     brouard  8692:   /* double ***mobaverage; */
1.126     brouard  8693:   char fileresf[FILENAMELENGTH];
                   8694: 
                   8695:   agelim=AGESUP;
1.211     brouard  8696:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8697:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8698:      We still use firstpass and lastpass as another selection.
                   8699:   */
1.214     brouard  8700:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8701:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8702:  
1.201     brouard  8703:   strcpy(fileresf,"F_"); 
                   8704:   strcat(fileresf,fileresu);
1.126     brouard  8705:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8706:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8707:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8708:   }
1.235     brouard  8709:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8710:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8711: 
1.225     brouard  8712:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8713: 
                   8714: 
                   8715:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8716:   if (stepm<=12) stepsize=1;
                   8717:   if(estepm < stepm){
                   8718:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8719:   }
1.270     brouard  8720:   else{
                   8721:     hstepm=estepm;   
                   8722:   }
                   8723:   if(estepm > stepm){ /* Yes every two year */
                   8724:     stepsize=2;
                   8725:   }
1.296     brouard  8726:   hstepm=hstepm/stepm;
1.126     brouard  8727: 
1.296     brouard  8728:   
                   8729:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8730:   /*                              fractional in yp1 *\/ */
                   8731:   /* aintmean=yp; */
                   8732:   /* yp2=modf((yp1*12),&yp); */
                   8733:   /* mintmean=yp; */
                   8734:   /* yp1=modf((yp2*30.5),&yp); */
                   8735:   /* jintmean=yp; */
                   8736:   /* if(jintmean==0) jintmean=1; */
                   8737:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8738: 
1.296     brouard  8739: 
                   8740:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8741:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8742:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8743:   i1=pow(2,cptcoveff);
1.126     brouard  8744:   if (cptcovn < 1){i1=1;}
                   8745:   
1.296     brouard  8746:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8747:   
                   8748:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8749:   
1.126     brouard  8750: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8751:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8752:   for(k=1; k<=i1;k++){
1.253     brouard  8753:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8754:       continue;
1.227     brouard  8755:     if(invalidvarcomb[k]){
                   8756:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8757:       continue;
                   8758:     }
                   8759:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8760:     for(j=1;j<=cptcoveff;j++) {
                   8761:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8762:     }
1.235     brouard  8763:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8764:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8765:     }
1.227     brouard  8766:     fprintf(ficresf," yearproj age");
                   8767:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8768:       for(i=1; i<=nlstate;i++)               
                   8769:        fprintf(ficresf," p%d%d",i,j);
                   8770:       fprintf(ficresf," wp.%d",j);
                   8771:     }
1.296     brouard  8772:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8773:       fprintf(ficresf,"\n");
1.296     brouard  8774:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8775:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8776:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8777:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8778:        nhstepm = nhstepm/hstepm; 
                   8779:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8780:        oldm=oldms;savm=savms;
1.268     brouard  8781:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8782:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8783:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8784:        for (h=0; h<=nhstepm; h++){
                   8785:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8786:            break;
                   8787:          }
                   8788:        }
                   8789:        fprintf(ficresf,"\n");
                   8790:        for(j=1;j<=cptcoveff;j++) 
                   8791:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8792:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8793:        
                   8794:        for(j=1; j<=nlstate+ndeath;j++) {
                   8795:          ppij=0.;
                   8796:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8797:            if (mobilav>=1)
                   8798:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8799:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8800:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8801:            }
1.268     brouard  8802:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8803:          } /* end i */
                   8804:          fprintf(ficresf," %.3f", ppij);
                   8805:        }/* end j */
1.227     brouard  8806:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8807:       } /* end agec */
1.266     brouard  8808:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8809:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8810:     } /* end yearp */
                   8811:   } /* end  k */
1.219     brouard  8812:        
1.126     brouard  8813:   fclose(ficresf);
1.215     brouard  8814:   printf("End of Computing forecasting \n");
                   8815:   fprintf(ficlog,"End of Computing forecasting\n");
                   8816: 
1.126     brouard  8817: }
                   8818: 
1.269     brouard  8819: /************** Back Forecasting ******************/
1.296     brouard  8820:  /* 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){ */
                   8821:  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){
                   8822:   /* back1, year, month, day of starting backprojection
1.267     brouard  8823:      agemin, agemax range of age
                   8824:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8825:      anback2 year of end of backprojection (same day and month as back1).
                   8826:      prevacurrent and prev are prevalences.
1.267     brouard  8827:   */
                   8828:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8829:   double agec; /* generic age */
1.302     brouard  8830:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8831:   double *popeffectif,*popcount;
                   8832:   double ***p3mat;
                   8833:   /* double ***mobaverage; */
                   8834:   char fileresfb[FILENAMELENGTH];
                   8835:  
1.268     brouard  8836:   agelim=AGEINF;
1.267     brouard  8837:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8838:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8839:      We still use firstpass and lastpass as another selection.
                   8840:   */
                   8841:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8842:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8843: 
                   8844:   /*Do we need to compute prevalence again?*/
                   8845: 
                   8846:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8847:   
                   8848:   strcpy(fileresfb,"FB_");
                   8849:   strcat(fileresfb,fileresu);
                   8850:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8851:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8852:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8853:   }
                   8854:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8855:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8856:   
                   8857:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8858:   
                   8859:    
                   8860:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8861:   if (stepm<=12) stepsize=1;
                   8862:   if(estepm < stepm){
                   8863:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8864:   }
1.270     brouard  8865:   else{
                   8866:     hstepm=estepm;   
                   8867:   }
                   8868:   if(estepm >= stepm){ /* Yes every two year */
                   8869:     stepsize=2;
                   8870:   }
1.267     brouard  8871:   
                   8872:   hstepm=hstepm/stepm;
1.296     brouard  8873:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8874:   /*                              fractional in yp1 *\/ */
                   8875:   /* aintmean=yp; */
                   8876:   /* yp2=modf((yp1*12),&yp); */
                   8877:   /* mintmean=yp; */
                   8878:   /* yp1=modf((yp2*30.5),&yp); */
                   8879:   /* jintmean=yp; */
                   8880:   /* if(jintmean==0) jintmean=1; */
                   8881:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8882:   
                   8883:   i1=pow(2,cptcoveff);
                   8884:   if (cptcovn < 1){i1=1;}
                   8885:   
1.296     brouard  8886:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8887:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8888:   
                   8889:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8890:   
                   8891:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8892:   for(k=1; k<=i1;k++){
                   8893:     if(i1 != 1 && TKresult[nres]!= k)
                   8894:       continue;
                   8895:     if(invalidvarcomb[k]){
                   8896:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8897:       continue;
                   8898:     }
1.268     brouard  8899:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8900:     for(j=1;j<=cptcoveff;j++) {
                   8901:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8902:     }
                   8903:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8904:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8905:     }
                   8906:     fprintf(ficresfb," yearbproj age");
                   8907:     for(j=1; j<=nlstate+ndeath;j++){
                   8908:       for(i=1; i<=nlstate;i++)
1.268     brouard  8909:        fprintf(ficresfb," b%d%d",i,j);
                   8910:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8911:     }
1.296     brouard  8912:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8913:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8914:       fprintf(ficresfb,"\n");
1.296     brouard  8915:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8916:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8917:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8918:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8919:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8920:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8921:        nhstepm = nhstepm/hstepm;
                   8922:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8923:        oldm=oldms;savm=savms;
1.268     brouard  8924:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8925:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8926:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8927:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8928:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8929:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8930:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8931:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8932:            break;
                   8933:          }
                   8934:        }
                   8935:        fprintf(ficresfb,"\n");
                   8936:        for(j=1;j<=cptcoveff;j++)
                   8937:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8938:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8939:        for(i=1; i<=nlstate+ndeath;i++) {
                   8940:          ppij=0.;ppi=0.;
                   8941:          for(j=1; j<=nlstate;j++) {
                   8942:            /* if (mobilav==1) */
1.269     brouard  8943:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8944:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8945:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8946:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8947:              /* else { */
                   8948:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8949:              /* } */
1.268     brouard  8950:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8951:          } /* end j */
                   8952:          if(ppi <0.99){
                   8953:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8954:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8955:          }
                   8956:          fprintf(ficresfb," %.3f", ppij);
                   8957:        }/* end j */
1.267     brouard  8958:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8959:       } /* end agec */
                   8960:     } /* end yearp */
                   8961:   } /* end k */
1.217     brouard  8962:   
1.267     brouard  8963:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8964:   
1.267     brouard  8965:   fclose(ficresfb);
                   8966:   printf("End of Computing Back forecasting \n");
                   8967:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8968:        
1.267     brouard  8969: }
1.217     brouard  8970: 
1.269     brouard  8971: /* Variance of prevalence limit: varprlim */
                   8972:  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  8973:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8974:  
                   8975:    char fileresvpl[FILENAMELENGTH];  
                   8976:    FILE *ficresvpl;
                   8977:    double **oldm, **savm;
                   8978:    double **varpl; /* Variances of prevalence limits by age */   
                   8979:    int i1, k, nres, j ;
                   8980:    
                   8981:     strcpy(fileresvpl,"VPL_");
                   8982:     strcat(fileresvpl,fileresu);
                   8983:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8984:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8985:       exit(0);
                   8986:     }
1.288     brouard  8987:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8988:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8989:     
                   8990:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8991:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8992:     
                   8993:     i1=pow(2,cptcoveff);
                   8994:     if (cptcovn < 1){i1=1;}
                   8995: 
                   8996:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8997:     for(k=1; k<=i1;k++){
                   8998:       if(i1 != 1 && TKresult[nres]!= k)
                   8999:        continue;
                   9000:       fprintf(ficresvpl,"\n#****** ");
                   9001:       printf("\n#****** ");
                   9002:       fprintf(ficlog,"\n#****** ");
                   9003:       for(j=1;j<=cptcoveff;j++) {
                   9004:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9005:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9006:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9007:       }
                   9008:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9009:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9010:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9011:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9012:       }        
                   9013:       fprintf(ficresvpl,"******\n");
                   9014:       printf("******\n");
                   9015:       fprintf(ficlog,"******\n");
                   9016:       
                   9017:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9018:       oldm=oldms;savm=savms;
                   9019:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9020:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9021:       /*}*/
                   9022:     }
                   9023:     
                   9024:     fclose(ficresvpl);
1.288     brouard  9025:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9026:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9027: 
                   9028:  }
                   9029: /* Variance of back prevalence: varbprlim */
                   9030:  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){
                   9031:       /*------- Variance of back (stable) prevalence------*/
                   9032: 
                   9033:    char fileresvbl[FILENAMELENGTH];  
                   9034:    FILE  *ficresvbl;
                   9035: 
                   9036:    double **oldm, **savm;
                   9037:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9038:    int i1, k, nres, j ;
                   9039: 
                   9040:    strcpy(fileresvbl,"VBL_");
                   9041:    strcat(fileresvbl,fileresu);
                   9042:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9043:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9044:      exit(0);
                   9045:    }
                   9046:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9047:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9048:    
                   9049:    
                   9050:    i1=pow(2,cptcoveff);
                   9051:    if (cptcovn < 1){i1=1;}
                   9052:    
                   9053:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9054:      for(k=1; k<=i1;k++){
                   9055:        if(i1 != 1 && TKresult[nres]!= k)
                   9056:         continue;
                   9057:        fprintf(ficresvbl,"\n#****** ");
                   9058:        printf("\n#****** ");
                   9059:        fprintf(ficlog,"\n#****** ");
                   9060:        for(j=1;j<=cptcoveff;j++) {
                   9061:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9062:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9063:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9064:        }
                   9065:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9066:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9067:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9068:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9069:        }
                   9070:        fprintf(ficresvbl,"******\n");
                   9071:        printf("******\n");
                   9072:        fprintf(ficlog,"******\n");
                   9073:        
                   9074:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9075:        oldm=oldms;savm=savms;
                   9076:        
                   9077:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9078:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9079:        /*}*/
                   9080:      }
                   9081:    
                   9082:    fclose(ficresvbl);
                   9083:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9084:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9085: 
                   9086:  } /* End of varbprlim */
                   9087: 
1.126     brouard  9088: /************** Forecasting *****not tested NB*************/
1.227     brouard  9089: /* 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  9090:   
1.227     brouard  9091: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9092: /*   int *popage; */
                   9093: /*   double calagedatem, agelim, kk1, kk2; */
                   9094: /*   double *popeffectif,*popcount; */
                   9095: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9096: /*   /\* double ***mobaverage; *\/ */
                   9097: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9098: 
1.227     brouard  9099: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9100: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9101: /*   agelim=AGESUP; */
                   9102: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9103:   
1.227     brouard  9104: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9105:   
                   9106:   
1.227     brouard  9107: /*   strcpy(filerespop,"POP_");  */
                   9108: /*   strcat(filerespop,fileresu); */
                   9109: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9110: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9111: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9112: /*   } */
                   9113: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9114: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9115: 
1.227     brouard  9116: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9117: 
1.227     brouard  9118: /*   /\* if (mobilav!=0) { *\/ */
                   9119: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9120: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9121: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9122: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9123: /*   /\*   } *\/ */
                   9124: /*   /\* } *\/ */
1.126     brouard  9125: 
1.227     brouard  9126: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9127: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9128:   
1.227     brouard  9129: /*   agelim=AGESUP; */
1.126     brouard  9130:   
1.227     brouard  9131: /*   hstepm=1; */
                   9132: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9133:        
1.227     brouard  9134: /*   if (popforecast==1) { */
                   9135: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9136: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9137: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9138: /*     }  */
                   9139: /*     popage=ivector(0,AGESUP); */
                   9140: /*     popeffectif=vector(0,AGESUP); */
                   9141: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9142:     
1.227     brouard  9143: /*     i=1;    */
                   9144: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9145:     
1.227     brouard  9146: /*     imx=i; */
                   9147: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9148: /*   } */
1.218     brouard  9149:   
1.227     brouard  9150: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9151: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9152: /*       k=k+1; */
                   9153: /*       fprintf(ficrespop,"\n#******"); */
                   9154: /*       for(j=1;j<=cptcoveff;j++) { */
                   9155: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9156: /*       } */
                   9157: /*       fprintf(ficrespop,"******\n"); */
                   9158: /*       fprintf(ficrespop,"# Age"); */
                   9159: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9160: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9161:       
1.227     brouard  9162: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9163: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9164:        
1.227     brouard  9165: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9166: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9167: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9168:          
1.227     brouard  9169: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9170: /*       oldm=oldms;savm=savms; */
                   9171: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9172:          
1.227     brouard  9173: /*       for (h=0; h<=nhstepm; h++){ */
                   9174: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9175: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9176: /*         }  */
                   9177: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9178: /*           kk1=0.;kk2=0; */
                   9179: /*           for(i=1; i<=nlstate;i++) {               */
                   9180: /*             if (mobilav==1)  */
                   9181: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9182: /*             else { */
                   9183: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9184: /*             } */
                   9185: /*           } */
                   9186: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9187: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9188: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9189: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9190: /*           } */
                   9191: /*         } */
                   9192: /*         for(i=1; i<=nlstate;i++){ */
                   9193: /*           kk1=0.; */
                   9194: /*           for(j=1; j<=nlstate;j++){ */
                   9195: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9196: /*           } */
                   9197: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9198: /*         } */
1.218     brouard  9199:            
1.227     brouard  9200: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9201: /*           for(j=1; j<=nlstate;j++)  */
                   9202: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9203: /*       } */
                   9204: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9205: /*     } */
                   9206: /*       } */
1.218     brouard  9207:       
1.227     brouard  9208: /*       /\******\/ */
1.218     brouard  9209:       
1.227     brouard  9210: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9211: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9212: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9213: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9214: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9215:          
1.227     brouard  9216: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9217: /*       oldm=oldms;savm=savms; */
                   9218: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9219: /*       for (h=0; h<=nhstepm; h++){ */
                   9220: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9221: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9222: /*         }  */
                   9223: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9224: /*           kk1=0.;kk2=0; */
                   9225: /*           for(i=1; i<=nlstate;i++) {               */
                   9226: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9227: /*           } */
                   9228: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9229: /*         } */
                   9230: /*       } */
                   9231: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9232: /*     } */
                   9233: /*       } */
                   9234: /*     }  */
                   9235: /*   } */
1.218     brouard  9236:   
1.227     brouard  9237: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9238:   
1.227     brouard  9239: /*   if (popforecast==1) { */
                   9240: /*     free_ivector(popage,0,AGESUP); */
                   9241: /*     free_vector(popeffectif,0,AGESUP); */
                   9242: /*     free_vector(popcount,0,AGESUP); */
                   9243: /*   } */
                   9244: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9245: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9246: /*   fclose(ficrespop); */
                   9247: /* } /\* End of popforecast *\/ */
1.218     brouard  9248:  
1.126     brouard  9249: int fileappend(FILE *fichier, char *optionfich)
                   9250: {
                   9251:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9252:     printf("Problem with file: %s\n", optionfich);
                   9253:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9254:     return (0);
                   9255:   }
                   9256:   fflush(fichier);
                   9257:   return (1);
                   9258: }
                   9259: 
                   9260: 
                   9261: /**************** function prwizard **********************/
                   9262: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9263: {
                   9264: 
                   9265:   /* Wizard to print covariance matrix template */
                   9266: 
1.164     brouard  9267:   char ca[32], cb[32];
                   9268:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9269:   int numlinepar;
                   9270: 
                   9271:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9272:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9273:   for(i=1; i <=nlstate; i++){
                   9274:     jj=0;
                   9275:     for(j=1; j <=nlstate+ndeath; j++){
                   9276:       if(j==i) continue;
                   9277:       jj++;
                   9278:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9279:       printf("%1d%1d",i,j);
                   9280:       fprintf(ficparo,"%1d%1d",i,j);
                   9281:       for(k=1; k<=ncovmodel;k++){
                   9282:        /*        printf(" %lf",param[i][j][k]); */
                   9283:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9284:        printf(" 0.");
                   9285:        fprintf(ficparo," 0.");
                   9286:       }
                   9287:       printf("\n");
                   9288:       fprintf(ficparo,"\n");
                   9289:     }
                   9290:   }
                   9291:   printf("# Scales (for hessian or gradient estimation)\n");
                   9292:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9293:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9294:   for(i=1; i <=nlstate; i++){
                   9295:     jj=0;
                   9296:     for(j=1; j <=nlstate+ndeath; j++){
                   9297:       if(j==i) continue;
                   9298:       jj++;
                   9299:       fprintf(ficparo,"%1d%1d",i,j);
                   9300:       printf("%1d%1d",i,j);
                   9301:       fflush(stdout);
                   9302:       for(k=1; k<=ncovmodel;k++){
                   9303:        /*      printf(" %le",delti3[i][j][k]); */
                   9304:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9305:        printf(" 0.");
                   9306:        fprintf(ficparo," 0.");
                   9307:       }
                   9308:       numlinepar++;
                   9309:       printf("\n");
                   9310:       fprintf(ficparo,"\n");
                   9311:     }
                   9312:   }
                   9313:   printf("# Covariance matrix\n");
                   9314: /* # 121 Var(a12)\n\ */
                   9315: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9316: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9317: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9318: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9319: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9320: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9321: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9322:   fflush(stdout);
                   9323:   fprintf(ficparo,"# Covariance matrix\n");
                   9324:   /* # 121 Var(a12)\n\ */
                   9325:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9326:   /* #   ...\n\ */
                   9327:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9328:   
                   9329:   for(itimes=1;itimes<=2;itimes++){
                   9330:     jj=0;
                   9331:     for(i=1; i <=nlstate; i++){
                   9332:       for(j=1; j <=nlstate+ndeath; j++){
                   9333:        if(j==i) continue;
                   9334:        for(k=1; k<=ncovmodel;k++){
                   9335:          jj++;
                   9336:          ca[0]= k+'a'-1;ca[1]='\0';
                   9337:          if(itimes==1){
                   9338:            printf("#%1d%1d%d",i,j,k);
                   9339:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9340:          }else{
                   9341:            printf("%1d%1d%d",i,j,k);
                   9342:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9343:            /*  printf(" %.5le",matcov[i][j]); */
                   9344:          }
                   9345:          ll=0;
                   9346:          for(li=1;li <=nlstate; li++){
                   9347:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9348:              if(lj==li) continue;
                   9349:              for(lk=1;lk<=ncovmodel;lk++){
                   9350:                ll++;
                   9351:                if(ll<=jj){
                   9352:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9353:                  if(ll<jj){
                   9354:                    if(itimes==1){
                   9355:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9356:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9357:                    }else{
                   9358:                      printf(" 0.");
                   9359:                      fprintf(ficparo," 0.");
                   9360:                    }
                   9361:                  }else{
                   9362:                    if(itimes==1){
                   9363:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9364:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9365:                    }else{
                   9366:                      printf(" 0.");
                   9367:                      fprintf(ficparo," 0.");
                   9368:                    }
                   9369:                  }
                   9370:                }
                   9371:              } /* end lk */
                   9372:            } /* end lj */
                   9373:          } /* end li */
                   9374:          printf("\n");
                   9375:          fprintf(ficparo,"\n");
                   9376:          numlinepar++;
                   9377:        } /* end k*/
                   9378:       } /*end j */
                   9379:     } /* end i */
                   9380:   } /* end itimes */
                   9381: 
                   9382: } /* end of prwizard */
                   9383: /******************* Gompertz Likelihood ******************************/
                   9384: double gompertz(double x[])
                   9385: { 
1.302     brouard  9386:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9387:   int i,n=0; /* n is the size of the sample */
                   9388: 
1.220     brouard  9389:   for (i=1;i<=imx ; i++) {
1.126     brouard  9390:     sump=sump+weight[i];
                   9391:     /*    sump=sump+1;*/
                   9392:     num=num+1;
                   9393:   }
1.302     brouard  9394:   L=0.0;
                   9395:   /* agegomp=AGEGOMP; */
1.126     brouard  9396:   /* for (i=0; i<=imx; i++) 
                   9397:      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]);*/
                   9398: 
1.302     brouard  9399:   for (i=1;i<=imx ; i++) {
                   9400:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9401:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9402:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9403:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9404:      * +
                   9405:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9406:      */
                   9407:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9408:        if (cens[i] == 1){
                   9409:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9410:        } else if (cens[i] == 0){
1.126     brouard  9411:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9412:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9413:       } else
                   9414:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9415:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9416:        L=L+A*weight[i];
1.126     brouard  9417:        /*      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  9418:      }
                   9419:   }
1.126     brouard  9420: 
1.302     brouard  9421:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9422:  
                   9423:   return -2*L*num/sump;
                   9424: }
                   9425: 
1.136     brouard  9426: #ifdef GSL
                   9427: /******************* Gompertz_f Likelihood ******************************/
                   9428: double gompertz_f(const gsl_vector *v, void *params)
                   9429: { 
1.302     brouard  9430:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9431:   double *x= (double *) v->data;
                   9432:   int i,n=0; /* n is the size of the sample */
                   9433: 
                   9434:   for (i=0;i<=imx-1 ; i++) {
                   9435:     sump=sump+weight[i];
                   9436:     /*    sump=sump+1;*/
                   9437:     num=num+1;
                   9438:   }
                   9439:  
                   9440:  
                   9441:   /* for (i=0; i<=imx; i++) 
                   9442:      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]);*/
                   9443:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9444:   for (i=1;i<=imx ; i++)
                   9445:     {
                   9446:       if (cens[i] == 1 && wav[i]>1)
                   9447:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9448:       
                   9449:       if (cens[i] == 0 && wav[i]>1)
                   9450:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9451:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9452:       
                   9453:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9454:       if (wav[i] > 1 ) { /* ??? */
                   9455:        LL=LL+A*weight[i];
                   9456:        /*      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]);*/
                   9457:       }
                   9458:     }
                   9459: 
                   9460:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9461:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9462:  
                   9463:   return -2*LL*num/sump;
                   9464: }
                   9465: #endif
                   9466: 
1.126     brouard  9467: /******************* Printing html file ***********/
1.201     brouard  9468: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9469:                  int lastpass, int stepm, int weightopt, char model[],\
                   9470:                  int imx,  double p[],double **matcov,double agemortsup){
                   9471:   int i,k;
                   9472: 
                   9473:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9474:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9475:   for (i=1;i<=2;i++) 
                   9476:     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  9477:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9478:   fprintf(fichtm,"</ul>");
                   9479: 
                   9480: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9481: 
                   9482:  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>");
                   9483: 
                   9484:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9485:    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]);
                   9486: 
                   9487:  
                   9488:   fflush(fichtm);
                   9489: }
                   9490: 
                   9491: /******************* Gnuplot file **************/
1.201     brouard  9492: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9493: 
                   9494:   char dirfileres[132],optfileres[132];
1.164     brouard  9495: 
1.126     brouard  9496:   int ng;
                   9497: 
                   9498: 
                   9499:   /*#ifdef windows */
                   9500:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9501:     /*#endif */
                   9502: 
                   9503: 
                   9504:   strcpy(dirfileres,optionfilefiname);
                   9505:   strcpy(optfileres,"vpl");
1.199     brouard  9506:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9507:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9508:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9509:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9510:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9511: 
                   9512: } 
                   9513: 
1.136     brouard  9514: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9515: {
1.126     brouard  9516: 
1.136     brouard  9517:   /*-------- data file ----------*/
                   9518:   FILE *fic;
                   9519:   char dummy[]="                         ";
1.240     brouard  9520:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9521:   int lstra;
1.136     brouard  9522:   int linei, month, year,iout;
1.302     brouard  9523:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9524:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9525:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9526:   char *stratrunc;
1.223     brouard  9527: 
1.240     brouard  9528:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9529:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9530: 
1.240     brouard  9531:   for(v=1; v <=ncovcol;v++){
                   9532:     DummyV[v]=0;
                   9533:     FixedV[v]=0;
                   9534:   }
                   9535:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9536:     DummyV[v]=1;
                   9537:     FixedV[v]=0;
                   9538:   }
                   9539:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9540:     DummyV[v]=0;
                   9541:     FixedV[v]=1;
                   9542:   }
                   9543:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9544:     DummyV[v]=1;
                   9545:     FixedV[v]=1;
                   9546:   }
                   9547:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9548:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9549:     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]);
                   9550:   }
1.126     brouard  9551: 
1.136     brouard  9552:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9553:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9554:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9555:   }
1.126     brouard  9556: 
1.302     brouard  9557:     /* Is it a BOM UTF-8 Windows file? */
                   9558:   /* First data line */
                   9559:   linei=0;
                   9560:   while(fgets(line, MAXLINE, fic)) {
                   9561:     noffset=0;
                   9562:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9563:     {
                   9564:       noffset=noffset+3;
                   9565:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9566:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9567:       fflush(ficlog); return 1;
                   9568:     }
                   9569:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9570:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9571:     {
                   9572:       noffset=noffset+2;
1.304     brouard  9573:       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);
                   9574:       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  9575:       fflush(ficlog); return 1;
                   9576:     }
                   9577:     else if( line[0] == 0 && line[1] == 0)
                   9578:     {
                   9579:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9580:        noffset=noffset+4;
1.304     brouard  9581:        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);
                   9582:        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  9583:        fflush(ficlog); return 1;
                   9584:       }
                   9585:     } else{
                   9586:       ;/*printf(" Not a BOM file\n");*/
                   9587:     }
                   9588:         /* If line starts with a # it is a comment */
                   9589:     if (line[noffset] == '#') {
                   9590:       linei=linei+1;
                   9591:       break;
                   9592:     }else{
                   9593:       break;
                   9594:     }
                   9595:   }
                   9596:   fclose(fic);
                   9597:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9598:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9599:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9600:   }
                   9601:   /* Not a Bom file */
                   9602:   
1.136     brouard  9603:   i=1;
                   9604:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9605:     linei=linei+1;
                   9606:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9607:       if(line[j] == '\t')
                   9608:        line[j] = ' ';
                   9609:     }
                   9610:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9611:       ;
                   9612:     };
                   9613:     line[j+1]=0;  /* Trims blanks at end of line */
                   9614:     if(line[0]=='#'){
                   9615:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9616:       printf("Comment line\n%s\n",line);
                   9617:       continue;
                   9618:     }
                   9619:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9620:     strcpy(line, linetmp);
1.223     brouard  9621:     
                   9622:     /* Loops on waves */
                   9623:     for (j=maxwav;j>=1;j--){
                   9624:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9625:        cutv(stra, strb, line, ' '); 
                   9626:        if(strb[0]=='.') { /* Missing value */
                   9627:          lval=-1;
                   9628:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9629:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9630:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9631:            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);
                   9632:            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);
                   9633:            return 1;
                   9634:          }
                   9635:        }else{
                   9636:          errno=0;
                   9637:          /* what_kind_of_number(strb); */
                   9638:          dval=strtod(strb,&endptr); 
                   9639:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9640:          /* if(strb != endptr && *endptr == '\0') */
                   9641:          /*    dval=dlval; */
                   9642:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9643:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9644:            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);
                   9645:            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);
                   9646:            return 1;
                   9647:          }
                   9648:          cotqvar[j][iv][i]=dval; 
                   9649:          cotvar[j][ntv+iv][i]=dval; 
                   9650:        }
                   9651:        strcpy(line,stra);
1.223     brouard  9652:       }/* end loop ntqv */
1.225     brouard  9653:       
1.223     brouard  9654:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9655:        cutv(stra, strb, line, ' '); 
                   9656:        if(strb[0]=='.') { /* Missing value */
                   9657:          lval=-1;
                   9658:        }else{
                   9659:          errno=0;
                   9660:          lval=strtol(strb,&endptr,10); 
                   9661:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9662:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9663:            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);
                   9664:            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);
                   9665:            return 1;
                   9666:          }
                   9667:        }
                   9668:        if(lval <-1 || lval >1){
                   9669:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9670:  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  9671:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9672:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9673:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9674:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9675:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9676:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9677:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  9678:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9679:  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  9680:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9681:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9682:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9683:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9684:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9685:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9686:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  9687:          return 1;
                   9688:        }
                   9689:        cotvar[j][iv][i]=(double)(lval);
                   9690:        strcpy(line,stra);
1.223     brouard  9691:       }/* end loop ntv */
1.225     brouard  9692:       
1.223     brouard  9693:       /* Statuses  at wave */
1.137     brouard  9694:       cutv(stra, strb, line, ' '); 
1.223     brouard  9695:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9696:        lval=-1;
1.136     brouard  9697:       }else{
1.238     brouard  9698:        errno=0;
                   9699:        lval=strtol(strb,&endptr,10); 
                   9700:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9701:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9702:          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);
                   9703:          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);
                   9704:          return 1;
                   9705:        }
1.136     brouard  9706:       }
1.225     brouard  9707:       
1.136     brouard  9708:       s[j][i]=lval;
1.225     brouard  9709:       
1.223     brouard  9710:       /* Date of Interview */
1.136     brouard  9711:       strcpy(line,stra);
                   9712:       cutv(stra, strb,line,' ');
1.169     brouard  9713:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9714:       }
1.169     brouard  9715:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9716:        month=99;
                   9717:        year=9999;
1.136     brouard  9718:       }else{
1.225     brouard  9719:        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);
                   9720:        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);
                   9721:        return 1;
1.136     brouard  9722:       }
                   9723:       anint[j][i]= (double) year; 
1.302     brouard  9724:       mint[j][i]= (double)month;
                   9725:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9726:       /*       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]); */
                   9727:       /*       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]); */
                   9728:       /* } */
1.136     brouard  9729:       strcpy(line,stra);
1.223     brouard  9730:     } /* End loop on waves */
1.225     brouard  9731:     
1.223     brouard  9732:     /* Date of death */
1.136     brouard  9733:     cutv(stra, strb,line,' '); 
1.169     brouard  9734:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9735:     }
1.169     brouard  9736:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9737:       month=99;
                   9738:       year=9999;
                   9739:     }else{
1.141     brouard  9740:       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  9741:       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);
                   9742:       return 1;
1.136     brouard  9743:     }
                   9744:     andc[i]=(double) year; 
                   9745:     moisdc[i]=(double) month; 
                   9746:     strcpy(line,stra);
                   9747:     
1.223     brouard  9748:     /* Date of birth */
1.136     brouard  9749:     cutv(stra, strb,line,' '); 
1.169     brouard  9750:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9751:     }
1.169     brouard  9752:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9753:       month=99;
                   9754:       year=9999;
                   9755:     }else{
1.141     brouard  9756:       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);
                   9757:       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  9758:       return 1;
1.136     brouard  9759:     }
                   9760:     if (year==9999) {
1.141     brouard  9761:       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);
                   9762:       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  9763:       return 1;
                   9764:       
1.136     brouard  9765:     }
                   9766:     annais[i]=(double)(year);
1.302     brouard  9767:     moisnais[i]=(double)(month);
                   9768:     for (j=1;j<=maxwav;j++){
                   9769:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9770:        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]);
                   9771:        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]);
                   9772:       }
                   9773:     }
                   9774: 
1.136     brouard  9775:     strcpy(line,stra);
1.225     brouard  9776:     
1.223     brouard  9777:     /* Sample weight */
1.136     brouard  9778:     cutv(stra, strb,line,' '); 
                   9779:     errno=0;
                   9780:     dval=strtod(strb,&endptr); 
                   9781:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9782:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9783:       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  9784:       fflush(ficlog);
                   9785:       return 1;
                   9786:     }
                   9787:     weight[i]=dval; 
                   9788:     strcpy(line,stra);
1.225     brouard  9789:     
1.223     brouard  9790:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9791:       cutv(stra, strb, line, ' '); 
                   9792:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9793:        lval=-1;
1.311     brouard  9794:        coqvar[iv][i]=NAN; 
                   9795:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9796:       }else{
1.225     brouard  9797:        errno=0;
                   9798:        /* what_kind_of_number(strb); */
                   9799:        dval=strtod(strb,&endptr);
                   9800:        /* if(strb != endptr && *endptr == '\0') */
                   9801:        /*   dval=dlval; */
                   9802:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9803:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9804:          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);
                   9805:          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);
                   9806:          return 1;
                   9807:        }
                   9808:        coqvar[iv][i]=dval; 
1.226     brouard  9809:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9810:       }
                   9811:       strcpy(line,stra);
                   9812:     }/* end loop nqv */
1.136     brouard  9813:     
1.223     brouard  9814:     /* Covariate values */
1.136     brouard  9815:     for (j=ncovcol;j>=1;j--){
                   9816:       cutv(stra, strb,line,' '); 
1.223     brouard  9817:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9818:        lval=-1;
1.136     brouard  9819:       }else{
1.225     brouard  9820:        errno=0;
                   9821:        lval=strtol(strb,&endptr,10); 
                   9822:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9823:          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);
                   9824:          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);
                   9825:          return 1;
                   9826:        }
1.136     brouard  9827:       }
                   9828:       if(lval <-1 || lval >1){
1.225     brouard  9829:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9830:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9831:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9832:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9833:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9834:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9835:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9836:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9837:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9838:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9839:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9840:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9841:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9842:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9843:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9844:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9845:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9846:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9847:        return 1;
1.136     brouard  9848:       }
                   9849:       covar[j][i]=(double)(lval);
                   9850:       strcpy(line,stra);
                   9851:     }  
                   9852:     lstra=strlen(stra);
1.225     brouard  9853:     
1.136     brouard  9854:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9855:       stratrunc = &(stra[lstra-9]);
                   9856:       num[i]=atol(stratrunc);
                   9857:     }
                   9858:     else
                   9859:       num[i]=atol(stra);
                   9860:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9861:       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;}*/
                   9862:     
                   9863:     i=i+1;
                   9864:   } /* End loop reading  data */
1.225     brouard  9865:   
1.136     brouard  9866:   *imax=i-1; /* Number of individuals */
                   9867:   fclose(fic);
1.225     brouard  9868:   
1.136     brouard  9869:   return (0);
1.164     brouard  9870:   /* endread: */
1.225     brouard  9871:   printf("Exiting readdata: ");
                   9872:   fclose(fic);
                   9873:   return (1);
1.223     brouard  9874: }
1.126     brouard  9875: 
1.234     brouard  9876: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9877:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9878:   while (*p2 == ' ')
1.234     brouard  9879:     p2++; 
                   9880:   /* while ((*p1++ = *p2++) !=0) */
                   9881:   /*   ; */
                   9882:   /* do */
                   9883:   /*   while (*p2 == ' ') */
                   9884:   /*     p2++; */
                   9885:   /* while (*p1++ == *p2++); */
                   9886:   *stri=p2; 
1.145     brouard  9887: }
                   9888: 
1.235     brouard  9889: int decoderesult ( char resultline[], int nres)
1.230     brouard  9890: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9891: {
1.235     brouard  9892:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9893:   char resultsav[MAXLINE];
1.234     brouard  9894:   int resultmodel[MAXLINE];
                   9895:   int modelresult[MAXLINE];
1.230     brouard  9896:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9897: 
1.234     brouard  9898:   removefirstspace(&resultline);
1.230     brouard  9899: 
                   9900:   if (strstr(resultline,"v") !=0){
                   9901:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9902:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9903:     return 1;
                   9904:   }
                   9905:   trimbb(resultsav, resultline);
                   9906:   if (strlen(resultsav) >1){
                   9907:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9908:   }
1.253     brouard  9909:   if(j == 0){ /* Resultline but no = */
                   9910:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9911:     return (0);
                   9912:   }
1.234     brouard  9913:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.318     brouard  9914:     printf("ERROR: the number of variables in this result line, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.310     brouard  9915:     fprintf(ficlog,"ERROR: the number of variables in the resultline, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.234     brouard  9916:   }
                   9917:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9918:     if(nbocc(resultsav,'=') >1){
1.318     brouard  9919:       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" */
                   9920:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.234     brouard  9921:     }else
                   9922:       cutl(strc,strd,resultsav,'=');
1.318     brouard  9923:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  9924:     
1.230     brouard  9925:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  9926:     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  9927:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9928:     /* cptcovsel++;     */
                   9929:     if (nbocc(stra,'=') >0)
                   9930:       strcpy(resultsav,stra); /* and analyzes it */
                   9931:   }
1.235     brouard  9932:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  9933:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on model. model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9934:     if(Typevar[k1]==0){ /* Single covariate in model *//*0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  9935:       match=0;
1.318     brouard  9936:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9937:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9938:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  9939:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  9940:          break;
                   9941:        }
                   9942:       }
                   9943:       if(match == 0){
1.310     brouard  9944:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9945:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9946:        return 1;
1.234     brouard  9947:       }
                   9948:     }
                   9949:   }
1.235     brouard  9950:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  9951:   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  9952:     match=0;
1.318     brouard  9953:     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.235     brouard  9954:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9955:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.318     brouard  9956:          resultmodel[k1]=k2;  /* k2th variable of the model corresponds to k1 variable of the model. resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9957:          ++match;
                   9958:        }
                   9959:       }
                   9960:     }
                   9961:     if(match == 0){
                   9962:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310     brouard  9963:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9964:       return 1;
1.234     brouard  9965:     }else if(match > 1){
                   9966:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  9967:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9968:       return 1;
1.234     brouard  9969:     }
                   9970:   }
1.235     brouard  9971:       
1.234     brouard  9972:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9973:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9974:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9975:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9976:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9977:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9978:   /*    1 0 0 0 */
                   9979:   /*    2 1 0 0 */
                   9980:   /*    3 0 1 0 */ 
                   9981:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9982:   /*    5 0 0 1 */
                   9983:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9984:   /*    7 0 1 1 */
                   9985:   /*    8 1 1 1 */
1.237     brouard  9986:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9987:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9988:   /* V5*age V5 known which value for nres?  */
                   9989:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.318     brouard  9990:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* loop on model line */
1.235     brouard  9991:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9992:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9993:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9994:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9995:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9996:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9997:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9998:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9999:       k4++;;
                   10000:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
1.318     brouard  10001:       k3q= resultmodel[k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   10002:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.237     brouard  10003:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10004:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   10005:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  10006:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   10007:       k4q++;;
                   10008:     }
                   10009:   }
1.234     brouard  10010:   
1.235     brouard  10011:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  10012:   return (0);
                   10013: }
1.235     brouard  10014: 
1.230     brouard  10015: int decodemodel( char model[], int lastobs)
                   10016:  /**< This routine decodes the model and returns:
1.224     brouard  10017:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10018:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10019:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10020:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10021:        * - cptcovage number of covariates with age*products =2
                   10022:        * - cptcovs number of simple covariates
                   10023:        * - 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
                   10024:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10025:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10026:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10027:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10028:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10029:        */
1.319     brouard  10030: /* 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  10031: {
1.238     brouard  10032:   int i, j, k, ks, v;
1.227     brouard  10033:   int  j1, k1, k2, k3, k4;
1.136     brouard  10034:   char modelsav[80];
1.145     brouard  10035:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10036:   char *strpt;
1.136     brouard  10037: 
1.145     brouard  10038:   /*removespace(model);*/
1.136     brouard  10039:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10040:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10041:     if (strstr(model,"AGE") !=0){
1.192     brouard  10042:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10043:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10044:       return 1;
                   10045:     }
1.141     brouard  10046:     if (strstr(model,"v") !=0){
                   10047:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10048:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10049:       return 1;
                   10050:     }
1.187     brouard  10051:     strcpy(modelsav,model); 
                   10052:     if ((strpt=strstr(model,"age*age")) !=0){
                   10053:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10054:       if(strpt != model){
1.234     brouard  10055:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10056:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10057:  corresponding column of parameters.\n",model);
1.234     brouard  10058:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10059:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10060:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10061:        return 1;
1.225     brouard  10062:       }
1.187     brouard  10063:       nagesqr=1;
                   10064:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10065:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10066:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10067:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10068:       else 
1.234     brouard  10069:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10070:     }else
                   10071:       nagesqr=0;
                   10072:     if (strlen(modelsav) >1){
                   10073:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10074:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10075:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10076:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10077:                     * cst, age and age*age 
                   10078:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10079:       /* including age products which are counted in cptcovage.
                   10080:        * but the covariates which are products must be treated 
                   10081:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10082:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10083:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10084:       
                   10085:       
1.187     brouard  10086:       /*   Design
                   10087:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10088:        *  <          ncovcol=8                >
                   10089:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10090:        *   k=  1    2      3       4     5       6      7        8
                   10091:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10092:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10093:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10094:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10095:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10096:        *  Tage[++cptcovage]=k
                   10097:        *       if products, new covar are created after ncovcol with k1
                   10098:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10099:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10100:        *  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
                   10101:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10102:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10103:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10104:        *  <          ncovcol=8                >
                   10105:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10106:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10107:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10108:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10109:        * p Tprod[1]@2={                         6, 5}
                   10110:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10111:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10112:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10113:        *How to reorganize? Tvars(orted)
1.187     brouard  10114:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10115:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10116:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10117:        * Struct []
                   10118:        */
1.225     brouard  10119:       
1.187     brouard  10120:       /* This loop fills the array Tvar from the string 'model'.*/
                   10121:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10122:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10123:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10124:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10125:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10126:       /*       k=1 Tvar[1]=2 (from V2) */
                   10127:       /*       k=5 Tvar[5] */
                   10128:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10129:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10130:       /*       } */
1.198     brouard  10131:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10132:       /*
                   10133:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10134:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10135:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10136:       }
1.187     brouard  10137:       cptcovage=0;
1.319     brouard  10138:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10139:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10140:                                         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" */
                   10141:        if (nbocc(modelsav,'+')==0)
                   10142:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10143:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10144:        /*scanf("%d",i);*/
1.319     brouard  10145:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10146:          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  10147:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10148:            /* covar is not filled and then is empty */
                   10149:            cptcovprod--;
                   10150:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10151:            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  10152:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10153:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10154:            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  10155:            /*printf("stre=%s ", stre);*/
                   10156:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10157:            cptcovprod--;
                   10158:            cutl(stre,strb,strc,'V');
                   10159:            Tvar[k]=atoi(stre);
                   10160:            Typevar[k]=1;  /* 1 for age product */
                   10161:            cptcovage++;
                   10162:            Tage[cptcovage]=k;
                   10163:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10164:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10165:            cptcovn++;
                   10166:            cptcovprodnoage++;k1++;
                   10167:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10168:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10169:                                                because this model-covariate is a construction we invent a new column
                   10170:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10171:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10172:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10173:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10174:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10175:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10176:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10177:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10178:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   10179:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   10180:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10181:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10182:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10183:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10184:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10185:            for (i=1; i<=lastobs;i++){
                   10186:              /* Computes the new covariate which is a product of
                   10187:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10188:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10189:            }
                   10190:          } /* End age is not in the model */
                   10191:        } /* End if model includes a product */
1.319     brouard  10192:        else { /* not a product */
1.234     brouard  10193:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10194:          /*  scanf("%d",i);*/
                   10195:          cutl(strd,strc,strb,'V');
                   10196:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10197:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10198:          Tvar[k]=atoi(strd);
                   10199:          Typevar[k]=0;  /* 0 for simple covariates */
                   10200:        }
                   10201:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10202:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10203:                                  scanf("%d",i);*/
1.187     brouard  10204:       } /* end of loop + on total covariates */
                   10205:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10206:   } /* end if strlen(model == 0) */
1.136     brouard  10207:   
                   10208:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10209:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10210:   
1.136     brouard  10211:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10212:      printf("cptcovprod=%d ", cptcovprod);
                   10213:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10214:      scanf("%d ",i);*/
                   10215: 
                   10216: 
1.230     brouard  10217: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10218:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10219: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10220:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10221:    k =           1    2   3     4       5       6      7      8        9
                   10222:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10223:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10224:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10225:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10226:          Tmodelind[combination of covar]=k;
1.225     brouard  10227: */  
                   10228: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10229:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10230:   /* 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  10231:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10232:   printf("Model=1+age+%s\n\
1.227     brouard  10233: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10234: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10235: 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  10236:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10237: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10238: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10239: 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  10240:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10241:   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 */
                   10242:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10243:       Fixed[k]= 0;
                   10244:       Dummy[k]= 0;
1.225     brouard  10245:       ncoveff++;
1.232     brouard  10246:       ncovf++;
1.234     brouard  10247:       nsd++;
                   10248:       modell[k].maintype= FTYPE;
                   10249:       TvarsD[nsd]=Tvar[k];
                   10250:       TvarsDind[nsd]=k;
                   10251:       TvarF[ncovf]=Tvar[k];
                   10252:       TvarFind[ncovf]=k;
                   10253:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10254:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10255:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10256:       Fixed[k]= 0;
                   10257:       Dummy[k]= 0;
                   10258:       ncoveff++;
                   10259:       ncovf++;
                   10260:       modell[k].maintype= FTYPE;
                   10261:       TvarF[ncovf]=Tvar[k];
                   10262:       TvarFind[ncovf]=k;
1.230     brouard  10263:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10264:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10265:     }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  10266:       Fixed[k]= 0;
                   10267:       Dummy[k]= 1;
1.230     brouard  10268:       nqfveff++;
1.234     brouard  10269:       modell[k].maintype= FTYPE;
                   10270:       modell[k].subtype= FQ;
                   10271:       nsq++;
                   10272:       TvarsQ[nsq]=Tvar[k];
                   10273:       TvarsQind[nsq]=k;
1.232     brouard  10274:       ncovf++;
1.234     brouard  10275:       TvarF[ncovf]=Tvar[k];
                   10276:       TvarFind[ncovf]=k;
1.231     brouard  10277:       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  10278:       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  10279:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10280:       Fixed[k]= 1;
                   10281:       Dummy[k]= 0;
1.225     brouard  10282:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10283:       modell[k].maintype= VTYPE;
                   10284:       modell[k].subtype= VD;
                   10285:       nsd++;
                   10286:       TvarsD[nsd]=Tvar[k];
                   10287:       TvarsDind[nsd]=k;
                   10288:       ncovv++; /* Only simple time varying variables */
                   10289:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10290:       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  10291:       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 */
                   10292:       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  10293:       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);
                   10294:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10295:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10296:       Fixed[k]= 1;
                   10297:       Dummy[k]= 1;
                   10298:       nqtveff++;
                   10299:       modell[k].maintype= VTYPE;
                   10300:       modell[k].subtype= VQ;
                   10301:       ncovv++; /* Only simple time varying variables */
                   10302:       nsq++;
1.319     brouard  10303:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */
1.234     brouard  10304:       TvarsQind[nsq]=k;
                   10305:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10306:       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  10307:       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 */
                   10308:       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  10309:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10310:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10311:       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  10312:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10313:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10314:       ncova++;
                   10315:       TvarA[ncova]=Tvar[k];
                   10316:       TvarAind[ncova]=k;
1.231     brouard  10317:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10318:        Fixed[k]= 2;
                   10319:        Dummy[k]= 2;
                   10320:        modell[k].maintype= ATYPE;
                   10321:        modell[k].subtype= APFD;
                   10322:        /* ncoveff++; */
1.227     brouard  10323:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10324:        Fixed[k]= 2;
                   10325:        Dummy[k]= 3;
                   10326:        modell[k].maintype= ATYPE;
                   10327:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10328:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10329:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10330:        Fixed[k]= 3;
                   10331:        Dummy[k]= 2;
                   10332:        modell[k].maintype= ATYPE;
                   10333:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10334:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10335:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10336:        Fixed[k]= 3;
                   10337:        Dummy[k]= 3;
                   10338:        modell[k].maintype= ATYPE;
                   10339:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10340:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10341:       }
                   10342:     }else if (Typevar[k] == 2) {  /* product without age */
                   10343:       k1=Tposprod[k];
                   10344:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10345:        if(Tvard[k1][2] <=ncovcol){
                   10346:          Fixed[k]= 1;
                   10347:          Dummy[k]= 0;
                   10348:          modell[k].maintype= FTYPE;
                   10349:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10350:          ncovf++; /* Fixed variables without age */
                   10351:          TvarF[ncovf]=Tvar[k];
                   10352:          TvarFind[ncovf]=k;
                   10353:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10354:          Fixed[k]= 0;  /* or 2 ?*/
                   10355:          Dummy[k]= 1;
                   10356:          modell[k].maintype= FTYPE;
                   10357:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10358:          ncovf++; /* Varying variables without age */
                   10359:          TvarF[ncovf]=Tvar[k];
                   10360:          TvarFind[ncovf]=k;
                   10361:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10362:          Fixed[k]= 1;
                   10363:          Dummy[k]= 0;
                   10364:          modell[k].maintype= VTYPE;
                   10365:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10366:          ncovv++; /* Varying variables without age */
                   10367:          TvarV[ncovv]=Tvar[k];
                   10368:          TvarVind[ncovv]=k;
                   10369:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10370:          Fixed[k]= 1;
                   10371:          Dummy[k]= 1;
                   10372:          modell[k].maintype= VTYPE;
                   10373:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10374:          ncovv++; /* Varying variables without age */
                   10375:          TvarV[ncovv]=Tvar[k];
                   10376:          TvarVind[ncovv]=k;
                   10377:        }
1.227     brouard  10378:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10379:        if(Tvard[k1][2] <=ncovcol){
                   10380:          Fixed[k]= 0;  /* or 2 ?*/
                   10381:          Dummy[k]= 1;
                   10382:          modell[k].maintype= FTYPE;
                   10383:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10384:          ncovf++; /* Fixed variables without age */
                   10385:          TvarF[ncovf]=Tvar[k];
                   10386:          TvarFind[ncovf]=k;
                   10387:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10388:          Fixed[k]= 1;
                   10389:          Dummy[k]= 1;
                   10390:          modell[k].maintype= VTYPE;
                   10391:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10392:          ncovv++; /* Varying variables without age */
                   10393:          TvarV[ncovv]=Tvar[k];
                   10394:          TvarVind[ncovv]=k;
                   10395:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10396:          Fixed[k]= 1;
                   10397:          Dummy[k]= 1;
                   10398:          modell[k].maintype= VTYPE;
                   10399:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10400:          ncovv++; /* Varying variables without age */
                   10401:          TvarV[ncovv]=Tvar[k];
                   10402:          TvarVind[ncovv]=k;
                   10403:          ncovv++; /* Varying variables without age */
                   10404:          TvarV[ncovv]=Tvar[k];
                   10405:          TvarVind[ncovv]=k;
                   10406:        }
1.227     brouard  10407:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10408:        if(Tvard[k1][2] <=ncovcol){
                   10409:          Fixed[k]= 1;
                   10410:          Dummy[k]= 1;
                   10411:          modell[k].maintype= VTYPE;
                   10412:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10413:          ncovv++; /* Varying variables without age */
                   10414:          TvarV[ncovv]=Tvar[k];
                   10415:          TvarVind[ncovv]=k;
                   10416:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10417:          Fixed[k]= 1;
                   10418:          Dummy[k]= 1;
                   10419:          modell[k].maintype= VTYPE;
                   10420:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10421:          ncovv++; /* Varying variables without age */
                   10422:          TvarV[ncovv]=Tvar[k];
                   10423:          TvarVind[ncovv]=k;
                   10424:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10425:          Fixed[k]= 1;
                   10426:          Dummy[k]= 0;
                   10427:          modell[k].maintype= VTYPE;
                   10428:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10429:          ncovv++; /* Varying variables without age */
                   10430:          TvarV[ncovv]=Tvar[k];
                   10431:          TvarVind[ncovv]=k;
                   10432:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10433:          Fixed[k]= 1;
                   10434:          Dummy[k]= 1;
                   10435:          modell[k].maintype= VTYPE;
                   10436:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10437:          ncovv++; /* Varying variables without age */
                   10438:          TvarV[ncovv]=Tvar[k];
                   10439:          TvarVind[ncovv]=k;
                   10440:        }
1.227     brouard  10441:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10442:        if(Tvard[k1][2] <=ncovcol){
                   10443:          Fixed[k]= 1;
                   10444:          Dummy[k]= 1;
                   10445:          modell[k].maintype= VTYPE;
                   10446:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10447:          ncovv++; /* Varying variables without age */
                   10448:          TvarV[ncovv]=Tvar[k];
                   10449:          TvarVind[ncovv]=k;
                   10450:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10451:          Fixed[k]= 1;
                   10452:          Dummy[k]= 1;
                   10453:          modell[k].maintype= VTYPE;
                   10454:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10455:          ncovv++; /* Varying variables without age */
                   10456:          TvarV[ncovv]=Tvar[k];
                   10457:          TvarVind[ncovv]=k;
                   10458:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10459:          Fixed[k]= 1;
                   10460:          Dummy[k]= 1;
                   10461:          modell[k].maintype= VTYPE;
                   10462:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10463:          ncovv++; /* Varying variables without age */
                   10464:          TvarV[ncovv]=Tvar[k];
                   10465:          TvarVind[ncovv]=k;
                   10466:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10467:          Fixed[k]= 1;
                   10468:          Dummy[k]= 1;
                   10469:          modell[k].maintype= VTYPE;
                   10470:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10471:          ncovv++; /* Varying variables without age */
                   10472:          TvarV[ncovv]=Tvar[k];
                   10473:          TvarVind[ncovv]=k;
                   10474:        }
1.227     brouard  10475:       }else{
1.240     brouard  10476:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10477:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10478:       } /*end k1*/
1.225     brouard  10479:     }else{
1.226     brouard  10480:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10481:       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  10482:     }
1.227     brouard  10483:     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  10484:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10485:     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]);
                   10486:   }
                   10487:   /* Searching for doublons in the model */
                   10488:   for(k1=1; k1<= cptcovt;k1++){
                   10489:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10490:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10491:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10492:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10493:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10494:            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]);
                   10495:            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  10496:            return(1);
                   10497:          }
                   10498:        }else if (Typevar[k1] ==2){
                   10499:          k3=Tposprod[k1];
                   10500:          k4=Tposprod[k2];
                   10501:          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])) ){
                   10502:            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]]);
                   10503:            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);
                   10504:            return(1);
                   10505:          }
                   10506:        }
1.227     brouard  10507:       }
                   10508:     }
1.225     brouard  10509:   }
                   10510:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10511:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10512:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10513:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10514:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10515:   /*endread:*/
1.225     brouard  10516:   printf("Exiting decodemodel: ");
                   10517:   return (1);
1.136     brouard  10518: }
                   10519: 
1.169     brouard  10520: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10521: {/* Check ages at death */
1.136     brouard  10522:   int i, m;
1.218     brouard  10523:   int firstone=0;
                   10524:   
1.136     brouard  10525:   for (i=1; i<=imx; i++) {
                   10526:     for(m=2; (m<= maxwav); m++) {
                   10527:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10528:        anint[m][i]=9999;
1.216     brouard  10529:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10530:          s[m][i]=-1;
1.136     brouard  10531:       }
                   10532:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10533:        *nberr = *nberr + 1;
1.218     brouard  10534:        if(firstone == 0){
                   10535:          firstone=1;
1.260     brouard  10536:        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  10537:        }
1.262     brouard  10538:        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  10539:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10540:       }
                   10541:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10542:        (*nberr)++;
1.259     brouard  10543:        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  10544:        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  10545:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10546:       }
                   10547:     }
                   10548:   }
                   10549: 
                   10550:   for (i=1; i<=imx; i++)  {
                   10551:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10552:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10553:       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  10554:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10555:          if(agedc[i]>0){
                   10556:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10557:              agev[m][i]=agedc[i];
1.214     brouard  10558:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10559:            }else {
1.136     brouard  10560:              if ((int)andc[i]!=9999){
                   10561:                nbwarn++;
                   10562:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10563:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10564:                agev[m][i]=-1;
                   10565:              }
                   10566:            }
1.169     brouard  10567:          } /* agedc > 0 */
1.214     brouard  10568:        } /* end if */
1.136     brouard  10569:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10570:                                 years but with the precision of a month */
                   10571:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10572:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10573:            agev[m][i]=1;
                   10574:          else if(agev[m][i] < *agemin){ 
                   10575:            *agemin=agev[m][i];
                   10576:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10577:          }
                   10578:          else if(agev[m][i] >*agemax){
                   10579:            *agemax=agev[m][i];
1.156     brouard  10580:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10581:          }
                   10582:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10583:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10584:        } /* en if 9*/
1.136     brouard  10585:        else { /* =9 */
1.214     brouard  10586:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10587:          agev[m][i]=1;
                   10588:          s[m][i]=-1;
                   10589:        }
                   10590:       }
1.214     brouard  10591:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10592:        agev[m][i]=1;
1.214     brouard  10593:       else{
                   10594:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10595:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10596:        agev[m][i]=0;
                   10597:       }
                   10598:     } /* End for lastpass */
                   10599:   }
1.136     brouard  10600:     
                   10601:   for (i=1; i<=imx; i++)  {
                   10602:     for(m=firstpass; (m<=lastpass); m++){
                   10603:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10604:        (*nberr)++;
1.136     brouard  10605:        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);     
                   10606:        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);     
                   10607:        return 1;
                   10608:       }
                   10609:     }
                   10610:   }
                   10611: 
                   10612:   /*for (i=1; i<=imx; i++){
                   10613:   for (m=firstpass; (m<lastpass); m++){
                   10614:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10615: }
                   10616: 
                   10617: }*/
                   10618: 
                   10619: 
1.139     brouard  10620:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10621:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10622: 
                   10623:   return (0);
1.164     brouard  10624:  /* endread:*/
1.136     brouard  10625:     printf("Exiting calandcheckages: ");
                   10626:     return (1);
                   10627: }
                   10628: 
1.172     brouard  10629: #if defined(_MSC_VER)
                   10630: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10631: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10632: //#include "stdafx.h"
                   10633: //#include <stdio.h>
                   10634: //#include <tchar.h>
                   10635: //#include <windows.h>
                   10636: //#include <iostream>
                   10637: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10638: 
                   10639: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10640: 
                   10641: BOOL IsWow64()
                   10642: {
                   10643:        BOOL bIsWow64 = FALSE;
                   10644: 
                   10645:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10646:        //  (HANDLE, PBOOL);
                   10647: 
                   10648:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10649: 
                   10650:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10651:        const char funcName[] = "IsWow64Process";
                   10652:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10653:                GetProcAddress(module, funcName);
                   10654: 
                   10655:        if (NULL != fnIsWow64Process)
                   10656:        {
                   10657:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10658:                        &bIsWow64))
                   10659:                        //throw std::exception("Unknown error");
                   10660:                        printf("Unknown error\n");
                   10661:        }
                   10662:        return bIsWow64 != FALSE;
                   10663: }
                   10664: #endif
1.177     brouard  10665: 
1.191     brouard  10666: void syscompilerinfo(int logged)
1.292     brouard  10667: {
                   10668: #include <stdint.h>
                   10669: 
                   10670:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10671:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10672:    /* /GS /W3 /Gy
                   10673:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10674:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10675:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10676:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10677:    */ 
                   10678:    /* 64 bits */
1.185     brouard  10679:    /*
                   10680:      /GS /W3 /Gy
                   10681:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10682:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10683:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10684:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10685:    /* Optimization are useless and O3 is slower than O2 */
                   10686:    /*
                   10687:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10688:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10689:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10690:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10691:    */
1.186     brouard  10692:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10693:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10694:       /PDB:"visual studio
                   10695:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10696:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10697:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10698:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10699:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10700:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10701:       uiAccess='false'"
                   10702:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10703:       /NOLOGO /TLBID:1
                   10704:    */
1.292     brouard  10705: 
                   10706: 
1.177     brouard  10707: #if defined __INTEL_COMPILER
1.178     brouard  10708: #if defined(__GNUC__)
                   10709:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10710: #endif
1.177     brouard  10711: #elif defined(__GNUC__) 
1.179     brouard  10712: #ifndef  __APPLE__
1.174     brouard  10713: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10714: #endif
1.177     brouard  10715:    struct utsname sysInfo;
1.178     brouard  10716:    int cross = CROSS;
                   10717:    if (cross){
                   10718:           printf("Cross-");
1.191     brouard  10719:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10720:    }
1.174     brouard  10721: #endif
                   10722: 
1.191     brouard  10723:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10724: #if defined(__clang__)
1.191     brouard  10725:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10726: #endif
                   10727: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10728:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10729: #endif
                   10730: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10731:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10732: #endif
                   10733: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10734:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10735: #endif
                   10736: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10737:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10738: #endif
                   10739: #if defined(_MSC_VER)
1.191     brouard  10740:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10741: #endif
                   10742: #if defined(__PGI)
1.191     brouard  10743:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10744: #endif
                   10745: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10746:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10747: #endif
1.191     brouard  10748:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10749:    
1.167     brouard  10750: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10751: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10752:     // Windows (x64 and x86)
1.191     brouard  10753:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10754: #elif __unix__ // all unices, not all compilers
                   10755:     // Unix
1.191     brouard  10756:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10757: #elif __linux__
                   10758:     // linux
1.191     brouard  10759:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10760: #elif __APPLE__
1.174     brouard  10761:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10762:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10763: #endif
                   10764: 
                   10765: /*  __MINGW32__          */
                   10766: /*  __CYGWIN__  */
                   10767: /* __MINGW64__  */
                   10768: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10769: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10770: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10771: /* _WIN64  // Defined for applications for Win64. */
                   10772: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10773: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10774: 
1.167     brouard  10775: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10776:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10777: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10778:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10779: #else
1.191     brouard  10780:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10781: #endif
                   10782: 
1.169     brouard  10783: #if defined(__GNUC__)
                   10784: # if defined(__GNUC_PATCHLEVEL__)
                   10785: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10786:                             + __GNUC_MINOR__ * 100 \
                   10787:                             + __GNUC_PATCHLEVEL__)
                   10788: # else
                   10789: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10790:                             + __GNUC_MINOR__ * 100)
                   10791: # endif
1.174     brouard  10792:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10793:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10794: 
                   10795:    if (uname(&sysInfo) != -1) {
                   10796:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10797:         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  10798:    }
                   10799:    else
                   10800:       perror("uname() error");
1.179     brouard  10801:    //#ifndef __INTEL_COMPILER 
                   10802: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10803:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10804:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10805: #endif
1.169     brouard  10806: #endif
1.172     brouard  10807: 
1.286     brouard  10808:    //   void main ()
1.172     brouard  10809:    //   {
1.169     brouard  10810: #if defined(_MSC_VER)
1.174     brouard  10811:    if (IsWow64()){
1.191     brouard  10812:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10813:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10814:    }
                   10815:    else{
1.191     brouard  10816:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10817:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10818:    }
1.172     brouard  10819:    //     printf("\nPress Enter to continue...");
                   10820:    //     getchar();
                   10821:    //   }
                   10822: 
1.169     brouard  10823: #endif
                   10824:    
1.167     brouard  10825: 
1.219     brouard  10826: }
1.136     brouard  10827: 
1.219     brouard  10828: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10829:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10830:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10831:   /* double ftolpl = 1.e-10; */
1.180     brouard  10832:   double age, agebase, agelim;
1.203     brouard  10833:   double tot;
1.180     brouard  10834: 
1.202     brouard  10835:   strcpy(filerespl,"PL_");
                   10836:   strcat(filerespl,fileresu);
                   10837:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10838:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10839:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10840:   }
1.288     brouard  10841:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10842:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10843:   pstamp(ficrespl);
1.288     brouard  10844:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10845:   fprintf(ficrespl,"#Age ");
                   10846:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10847:   fprintf(ficrespl,"\n");
1.180     brouard  10848:   
1.219     brouard  10849:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10850: 
1.219     brouard  10851:   agebase=ageminpar;
                   10852:   agelim=agemaxpar;
1.180     brouard  10853: 
1.227     brouard  10854:   /* i1=pow(2,ncoveff); */
1.234     brouard  10855:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10856:   if (cptcovn < 1){i1=1;}
1.180     brouard  10857: 
1.238     brouard  10858:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10859:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10860:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10861:        continue;
1.235     brouard  10862: 
1.238     brouard  10863:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10864:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10865:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10866:       /* k=k+1; */
                   10867:       /* to clean */
                   10868:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10869:       fprintf(ficrespl,"#******");
                   10870:       printf("#******");
                   10871:       fprintf(ficlog,"#******");
                   10872:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10873:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10874:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10875:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10876:       }
                   10877:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10878:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10879:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10880:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10881:       }
                   10882:       fprintf(ficrespl,"******\n");
                   10883:       printf("******\n");
                   10884:       fprintf(ficlog,"******\n");
                   10885:       if(invalidvarcomb[k]){
                   10886:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10887:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10888:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10889:        continue;
                   10890:       }
1.219     brouard  10891: 
1.238     brouard  10892:       fprintf(ficrespl,"#Age ");
                   10893:       for(j=1;j<=cptcoveff;j++) {
                   10894:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10895:       }
                   10896:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10897:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10898:     
1.238     brouard  10899:       for (age=agebase; age<=agelim; age++){
                   10900:        /* for (age=agebase; age<=agebase; age++){ */
                   10901:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10902:        fprintf(ficrespl,"%.0f ",age );
                   10903:        for(j=1;j<=cptcoveff;j++)
                   10904:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10905:        tot=0.;
                   10906:        for(i=1; i<=nlstate;i++){
                   10907:          tot +=  prlim[i][i];
                   10908:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10909:        }
                   10910:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10911:       } /* Age */
                   10912:       /* was end of cptcod */
                   10913:     } /* cptcov */
                   10914:   } /* nres */
1.219     brouard  10915:   return 0;
1.180     brouard  10916: }
                   10917: 
1.218     brouard  10918: 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  10919:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10920:        
                   10921:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10922:    * at any age between ageminpar and agemaxpar
                   10923:         */
1.235     brouard  10924:   int i, j, k, i1, nres=0 ;
1.217     brouard  10925:   /* double ftolpl = 1.e-10; */
                   10926:   double age, agebase, agelim;
                   10927:   double tot;
1.218     brouard  10928:   /* double ***mobaverage; */
                   10929:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10930: 
                   10931:   strcpy(fileresplb,"PLB_");
                   10932:   strcat(fileresplb,fileresu);
                   10933:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10934:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10935:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10936:   }
1.288     brouard  10937:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10938:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10939:   pstamp(ficresplb);
1.288     brouard  10940:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10941:   fprintf(ficresplb,"#Age ");
                   10942:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10943:   fprintf(ficresplb,"\n");
                   10944:   
1.218     brouard  10945:   
                   10946:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10947:   
                   10948:   agebase=ageminpar;
                   10949:   agelim=agemaxpar;
                   10950:   
                   10951:   
1.227     brouard  10952:   i1=pow(2,cptcoveff);
1.218     brouard  10953:   if (cptcovn < 1){i1=1;}
1.227     brouard  10954:   
1.238     brouard  10955:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10956:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10957:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10958:        continue;
                   10959:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10960:       fprintf(ficresplb,"#******");
                   10961:       printf("#******");
                   10962:       fprintf(ficlog,"#******");
                   10963:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10964:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10965:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10966:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10967:       }
                   10968:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10969:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10970:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10971:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10972:       }
                   10973:       fprintf(ficresplb,"******\n");
                   10974:       printf("******\n");
                   10975:       fprintf(ficlog,"******\n");
                   10976:       if(invalidvarcomb[k]){
                   10977:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10978:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10979:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10980:        continue;
                   10981:       }
1.218     brouard  10982:     
1.238     brouard  10983:       fprintf(ficresplb,"#Age ");
                   10984:       for(j=1;j<=cptcoveff;j++) {
                   10985:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10986:       }
                   10987:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10988:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10989:     
                   10990:     
1.238     brouard  10991:       for (age=agebase; age<=agelim; age++){
                   10992:        /* for (age=agebase; age<=agebase; age++){ */
                   10993:        if(mobilavproj > 0){
                   10994:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10995:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10996:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10997:        }else if (mobilavproj == 0){
                   10998:          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);
                   10999:          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);
                   11000:          exit(1);
                   11001:        }else{
                   11002:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11003:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11004:          /* printf("TOTOT\n"); */
                   11005:           /* exit(1); */
1.238     brouard  11006:        }
                   11007:        fprintf(ficresplb,"%.0f ",age );
                   11008:        for(j=1;j<=cptcoveff;j++)
                   11009:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11010:        tot=0.;
                   11011:        for(i=1; i<=nlstate;i++){
                   11012:          tot +=  bprlim[i][i];
                   11013:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11014:        }
                   11015:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11016:       } /* Age */
                   11017:       /* was end of cptcod */
1.255     brouard  11018:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11019:     } /* end of any combination */
                   11020:   } /* end of nres */  
1.218     brouard  11021:   /* hBijx(p, bage, fage); */
                   11022:   /* fclose(ficrespijb); */
                   11023:   
                   11024:   return 0;
1.217     brouard  11025: }
1.218     brouard  11026:  
1.180     brouard  11027: int hPijx(double *p, int bage, int fage){
                   11028:     /*------------- h Pij x at various ages ------------*/
                   11029: 
                   11030:   int stepsize;
                   11031:   int agelim;
                   11032:   int hstepm;
                   11033:   int nhstepm;
1.235     brouard  11034:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11035: 
                   11036:   double agedeb;
                   11037:   double ***p3mat;
                   11038: 
1.201     brouard  11039:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11040:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11041:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11042:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11043:     }
                   11044:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11045:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11046:   
                   11047:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11048:     /*if (stepm<=24) stepsize=2;*/
                   11049: 
                   11050:     agelim=AGESUP;
                   11051:     hstepm=stepsize*YEARM; /* Every year of age */
                   11052:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11053:                
1.180     brouard  11054:     /* hstepm=1;   aff par mois*/
                   11055:     pstamp(ficrespij);
                   11056:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11057:     i1= pow(2,cptcoveff);
1.218     brouard  11058:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11059:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11060:                /*      k=k+1;  */
1.235     brouard  11061:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11062:     for(k=1; k<=i1;k++){
1.253     brouard  11063:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11064:        continue;
1.183     brouard  11065:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11066:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  11067:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11068:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11069:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11070:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11071:       }
1.183     brouard  11072:       fprintf(ficrespij,"******\n");
                   11073:       
                   11074:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11075:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11076:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11077:        
                   11078:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11079:        
1.183     brouard  11080:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11081:        oldm=oldms;savm=savms;
1.235     brouard  11082:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11083:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11084:        for(i=1; i<=nlstate;i++)
                   11085:          for(j=1; j<=nlstate+ndeath;j++)
                   11086:            fprintf(ficrespij," %1d-%1d",i,j);
                   11087:        fprintf(ficrespij,"\n");
                   11088:        for (h=0; h<=nhstepm; h++){
                   11089:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11090:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11091:          for(i=1; i<=nlstate;i++)
                   11092:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11093:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11094:          fprintf(ficrespij,"\n");
                   11095:        }
1.183     brouard  11096:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11097:        fprintf(ficrespij,"\n");
                   11098:       }
1.180     brouard  11099:       /*}*/
                   11100:     }
1.218     brouard  11101:     return 0;
1.180     brouard  11102: }
1.218     brouard  11103:  
                   11104:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11105:     /*------------- h Bij x at various ages ------------*/
                   11106: 
                   11107:   int stepsize;
1.218     brouard  11108:   /* int agelim; */
                   11109:        int ageminl;
1.217     brouard  11110:   int hstepm;
                   11111:   int nhstepm;
1.238     brouard  11112:   int h, i, i1, j, k, nres;
1.218     brouard  11113:        
1.217     brouard  11114:   double agedeb;
                   11115:   double ***p3mat;
1.218     brouard  11116:        
                   11117:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11118:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11119:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11120:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11121:   }
                   11122:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11123:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11124:   
                   11125:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11126:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11127:   
1.218     brouard  11128:   /* agelim=AGESUP; */
1.289     brouard  11129:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11130:   hstepm=stepsize*YEARM; /* Every year of age */
                   11131:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11132:   
                   11133:   /* hstepm=1;   aff par mois*/
                   11134:   pstamp(ficrespijb);
1.255     brouard  11135:   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  11136:   i1= pow(2,cptcoveff);
1.218     brouard  11137:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11138:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11139:   /*   k=k+1;  */
1.238     brouard  11140:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11141:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11142:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11143:        continue;
                   11144:       fprintf(ficrespijb,"\n#****** ");
                   11145:       for(j=1;j<=cptcoveff;j++)
                   11146:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11147:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11148:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11149:       }
                   11150:       fprintf(ficrespijb,"******\n");
1.264     brouard  11151:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11152:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11153:        continue;
                   11154:       }
                   11155:       
                   11156:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11157:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11158:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11159:        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 */
                   11160:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11161:        
                   11162:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11163:        
1.266     brouard  11164:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11165:        /* and memory limitations if stepm is small */
                   11166: 
1.238     brouard  11167:        /* oldm=oldms;savm=savms; */
                   11168:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  11169:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  11170:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11171:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11172:        for(i=1; i<=nlstate;i++)
                   11173:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11174:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11175:        fprintf(ficrespijb,"\n");
1.238     brouard  11176:        for (h=0; h<=nhstepm; h++){
                   11177:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11178:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11179:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11180:          for(i=1; i<=nlstate;i++)
                   11181:            for(j=1; j<=nlstate+ndeath;j++)
                   11182:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   11183:          fprintf(ficrespijb,"\n");
                   11184:        }
                   11185:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11186:        fprintf(ficrespijb,"\n");
                   11187:       } /* end age deb */
                   11188:     } /* end combination */
                   11189:   } /* end nres */
1.218     brouard  11190:   return 0;
                   11191:  } /*  hBijx */
1.217     brouard  11192: 
1.180     brouard  11193: 
1.136     brouard  11194: /***********************************************/
                   11195: /**************** Main Program *****************/
                   11196: /***********************************************/
                   11197: 
                   11198: int main(int argc, char *argv[])
                   11199: {
                   11200: #ifdef GSL
                   11201:   const gsl_multimin_fminimizer_type *T;
                   11202:   size_t iteri = 0, it;
                   11203:   int rval = GSL_CONTINUE;
                   11204:   int status = GSL_SUCCESS;
                   11205:   double ssval;
                   11206: #endif
                   11207:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11208:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11209:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11210:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11211:   int jj, ll, li, lj, lk;
1.136     brouard  11212:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11213:   int num_filled;
1.136     brouard  11214:   int itimes;
                   11215:   int NDIM=2;
                   11216:   int vpopbased=0;
1.235     brouard  11217:   int nres=0;
1.258     brouard  11218:   int endishere=0;
1.277     brouard  11219:   int noffset=0;
1.274     brouard  11220:   int ncurrv=0; /* Temporary variable */
                   11221:   
1.164     brouard  11222:   char ca[32], cb[32];
1.136     brouard  11223:   /*  FILE *fichtm; *//* Html File */
                   11224:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11225:   struct stat info;
1.191     brouard  11226:   double agedeb=0.;
1.194     brouard  11227: 
                   11228:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11229:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11230: 
1.165     brouard  11231:   double fret;
1.191     brouard  11232:   double dum=0.; /* Dummy variable */
1.136     brouard  11233:   double ***p3mat;
1.218     brouard  11234:   /* double ***mobaverage; */
1.319     brouard  11235:   double wald;
1.164     brouard  11236: 
                   11237:   char line[MAXLINE];
1.197     brouard  11238:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11239: 
1.234     brouard  11240:   char  modeltemp[MAXLINE];
1.230     brouard  11241:   char resultline[MAXLINE];
                   11242:   
1.136     brouard  11243:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11244:   char *tok, *val; /* pathtot */
1.290     brouard  11245:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11246:   int c,  h , cpt, c2;
1.191     brouard  11247:   int jl=0;
                   11248:   int i1, j1, jk, stepsize=0;
1.194     brouard  11249:   int count=0;
                   11250: 
1.164     brouard  11251:   int *tab; 
1.136     brouard  11252:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11253:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11254:   /* double anprojf, mprojf, jprojf; */
                   11255:   /* double jintmean,mintmean,aintmean;   */
                   11256:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11257:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11258:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11259:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11260:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11261:   int mobilav=0,popforecast=0;
1.191     brouard  11262:   int hstepm=0, nhstepm=0;
1.136     brouard  11263:   int agemortsup;
                   11264:   float  sumlpop=0.;
                   11265:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11266:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11267: 
1.191     brouard  11268:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11269:   double ftolpl=FTOL;
                   11270:   double **prlim;
1.217     brouard  11271:   double **bprlim;
1.317     brouard  11272:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11273:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11274:   double ***paramstart; /* Matrix of starting parameter values */
                   11275:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11276:   double **matcov; /* Matrix of covariance */
1.203     brouard  11277:   double **hess; /* Hessian matrix */
1.136     brouard  11278:   double ***delti3; /* Scale */
                   11279:   double *delti; /* Scale */
                   11280:   double ***eij, ***vareij;
                   11281:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11282: 
1.136     brouard  11283:   double *epj, vepp;
1.164     brouard  11284: 
1.273     brouard  11285:   double dateprev1, dateprev2;
1.296     brouard  11286:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11287:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11288: 
1.217     brouard  11289: 
1.136     brouard  11290:   double **ximort;
1.145     brouard  11291:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11292:   int *dcwave;
                   11293: 
1.164     brouard  11294:   char z[1]="c";
1.136     brouard  11295: 
                   11296:   /*char  *strt;*/
                   11297:   char strtend[80];
1.126     brouard  11298: 
1.164     brouard  11299: 
1.126     brouard  11300: /*   setlocale (LC_ALL, ""); */
                   11301: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11302: /*   textdomain (PACKAGE); */
                   11303: /*   setlocale (LC_CTYPE, ""); */
                   11304: /*   setlocale (LC_MESSAGES, ""); */
                   11305: 
                   11306:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11307:   rstart_time = time(NULL);  
                   11308:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11309:   start_time = *localtime(&rstart_time);
1.126     brouard  11310:   curr_time=start_time;
1.157     brouard  11311:   /*tml = *localtime(&start_time.tm_sec);*/
                   11312:   /* strcpy(strstart,asctime(&tml)); */
                   11313:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11314: 
                   11315: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11316: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11317: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11318: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11319: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11320: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11321: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11322: /*   strt=asctime(&tmg); */
                   11323: /*   printf("Time(after) =%s",strstart);  */
                   11324: /*  (void) time (&time_value);
                   11325: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11326: *  tm = *localtime(&time_value);
                   11327: *  strstart=asctime(&tm);
                   11328: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11329: */
                   11330: 
                   11331:   nberr=0; /* Number of errors and warnings */
                   11332:   nbwarn=0;
1.184     brouard  11333: #ifdef WIN32
                   11334:   _getcwd(pathcd, size);
                   11335: #else
1.126     brouard  11336:   getcwd(pathcd, size);
1.184     brouard  11337: #endif
1.191     brouard  11338:   syscompilerinfo(0);
1.196     brouard  11339:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11340:   if(argc <=1){
                   11341:     printf("\nEnter the parameter file name: ");
1.205     brouard  11342:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11343:       printf("ERROR Empty parameter file name\n");
                   11344:       goto end;
                   11345:     }
1.126     brouard  11346:     i=strlen(pathr);
                   11347:     if(pathr[i-1]=='\n')
                   11348:       pathr[i-1]='\0';
1.156     brouard  11349:     i=strlen(pathr);
1.205     brouard  11350:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11351:       pathr[i-1]='\0';
1.205     brouard  11352:     }
                   11353:     i=strlen(pathr);
                   11354:     if( i==0 ){
                   11355:       printf("ERROR Empty parameter file name\n");
                   11356:       goto end;
                   11357:     }
                   11358:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11359:       printf("Pathr |%s|\n",pathr);
                   11360:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11361:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11362:       strcpy (pathtot, val);
                   11363:       if(pathr[0] == '\0') break; /* Dirty */
                   11364:     }
                   11365:   }
1.281     brouard  11366:   else if (argc<=2){
                   11367:     strcpy(pathtot,argv[1]);
                   11368:   }
1.126     brouard  11369:   else{
                   11370:     strcpy(pathtot,argv[1]);
1.281     brouard  11371:     strcpy(z,argv[2]);
                   11372:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11373:   }
                   11374:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11375:   /*cygwin_split_path(pathtot,path,optionfile);
                   11376:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11377:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11378: 
                   11379:   /* Split argv[0], imach program to get pathimach */
                   11380:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11381:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11382:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11383:  /*   strcpy(pathimach,argv[0]); */
                   11384:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11385:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11386:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11387: #ifdef WIN32
                   11388:   _chdir(path); /* Can be a relative path */
                   11389:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11390: #else
1.126     brouard  11391:   chdir(path); /* Can be a relative path */
1.184     brouard  11392:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11393: #endif
                   11394:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11395:   strcpy(command,"mkdir ");
                   11396:   strcat(command,optionfilefiname);
                   11397:   if((outcmd=system(command)) != 0){
1.169     brouard  11398:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11399:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11400:     /* fclose(ficlog); */
                   11401: /*     exit(1); */
                   11402:   }
                   11403: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11404: /*     perror("mkdir"); */
                   11405: /*   } */
                   11406: 
                   11407:   /*-------- arguments in the command line --------*/
                   11408: 
1.186     brouard  11409:   /* Main Log file */
1.126     brouard  11410:   strcat(filelog, optionfilefiname);
                   11411:   strcat(filelog,".log");    /* */
                   11412:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11413:     printf("Problem with logfile %s\n",filelog);
                   11414:     goto end;
                   11415:   }
                   11416:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11417:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11418:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11419:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11420:  path=%s \n\
                   11421:  optionfile=%s\n\
                   11422:  optionfilext=%s\n\
1.156     brouard  11423:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11424: 
1.197     brouard  11425:   syscompilerinfo(1);
1.167     brouard  11426: 
1.126     brouard  11427:   printf("Local time (at start):%s",strstart);
                   11428:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11429:   fflush(ficlog);
                   11430: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11431: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11432: 
                   11433:   /* */
                   11434:   strcpy(fileres,"r");
                   11435:   strcat(fileres, optionfilefiname);
1.201     brouard  11436:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11437:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11438:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11439: 
1.186     brouard  11440:   /* Main ---------arguments file --------*/
1.126     brouard  11441: 
                   11442:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11443:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11444:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11445:     fflush(ficlog);
1.149     brouard  11446:     /* goto end; */
                   11447:     exit(70); 
1.126     brouard  11448:   }
                   11449: 
                   11450:   strcpy(filereso,"o");
1.201     brouard  11451:   strcat(filereso,fileresu);
1.126     brouard  11452:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11453:     printf("Problem with Output resultfile: %s\n", filereso);
                   11454:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11455:     fflush(ficlog);
                   11456:     goto end;
                   11457:   }
1.278     brouard  11458:       /*-------- Rewriting parameter file ----------*/
                   11459:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11460:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11461:   strcat(rfileres,".");    /* */
                   11462:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11463:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11464:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11465:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11466:     fflush(ficlog);
                   11467:     goto end;
                   11468:   }
                   11469:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11470: 
1.278     brouard  11471:                                      
1.126     brouard  11472:   /* Reads comments: lines beginning with '#' */
                   11473:   numlinepar=0;
1.277     brouard  11474:   /* Is it a BOM UTF-8 Windows file? */
                   11475:   /* First parameter line */
1.197     brouard  11476:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11477:     noffset=0;
                   11478:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11479:     {
                   11480:       noffset=noffset+3;
                   11481:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11482:     }
1.302     brouard  11483: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11484:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11485:     {
                   11486:       noffset=noffset+2;
                   11487:       printf("# File is an UTF16BE BOM file\n");
                   11488:     }
                   11489:     else if( line[0] == 0 && line[1] == 0)
                   11490:     {
                   11491:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11492:        noffset=noffset+4;
                   11493:        printf("# File is an UTF16BE BOM file\n");
                   11494:       }
                   11495:     } else{
                   11496:       ;/*printf(" Not a BOM file\n");*/
                   11497:     }
                   11498:   
1.197     brouard  11499:     /* If line starts with a # it is a comment */
1.277     brouard  11500:     if (line[noffset] == '#') {
1.197     brouard  11501:       numlinepar++;
                   11502:       fputs(line,stdout);
                   11503:       fputs(line,ficparo);
1.278     brouard  11504:       fputs(line,ficres);
1.197     brouard  11505:       fputs(line,ficlog);
                   11506:       continue;
                   11507:     }else
                   11508:       break;
                   11509:   }
                   11510:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11511:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11512:     if (num_filled != 5) {
                   11513:       printf("Should be 5 parameters\n");
1.283     brouard  11514:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11515:     }
1.126     brouard  11516:     numlinepar++;
1.197     brouard  11517:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11518:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11519:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11520:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11521:   }
                   11522:   /* Second parameter line */
                   11523:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11524:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11525:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11526:     if (line[0] == '#') {
                   11527:       numlinepar++;
1.283     brouard  11528:       printf("%s",line);
                   11529:       fprintf(ficres,"%s",line);
                   11530:       fprintf(ficparo,"%s",line);
                   11531:       fprintf(ficlog,"%s",line);
1.197     brouard  11532:       continue;
                   11533:     }else
                   11534:       break;
                   11535:   }
1.223     brouard  11536:   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", \
                   11537:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11538:     if (num_filled != 11) {
                   11539:       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  11540:       printf("but line=%s\n",line);
1.283     brouard  11541:       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");
                   11542:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11543:     }
1.286     brouard  11544:     if( lastpass > maxwav){
                   11545:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11546:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11547:       fflush(ficlog);
                   11548:       goto end;
                   11549:     }
                   11550:       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  11551:     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  11552:     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  11553:     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  11554:   }
1.203     brouard  11555:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11556:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11557:   /* Third parameter line */
                   11558:   while(fgets(line, MAXLINE, ficpar)) {
                   11559:     /* If line starts with a # it is a comment */
                   11560:     if (line[0] == '#') {
                   11561:       numlinepar++;
1.283     brouard  11562:       printf("%s",line);
                   11563:       fprintf(ficres,"%s",line);
                   11564:       fprintf(ficparo,"%s",line);
                   11565:       fprintf(ficlog,"%s",line);
1.197     brouard  11566:       continue;
                   11567:     }else
                   11568:       break;
                   11569:   }
1.201     brouard  11570:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11571:     if (num_filled != 1){
1.302     brouard  11572:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11573:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11574:       model[0]='\0';
                   11575:       goto end;
                   11576:     }
                   11577:     else{
                   11578:       if (model[0]=='+'){
                   11579:        for(i=1; i<=strlen(model);i++)
                   11580:          modeltemp[i-1]=model[i];
1.201     brouard  11581:        strcpy(model,modeltemp); 
1.197     brouard  11582:       }
                   11583:     }
1.199     brouard  11584:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11585:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11586:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11587:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11588:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11589:   }
                   11590:   /* 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); */
                   11591:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11592:   /* 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  11593:   /* 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); */
                   11594:   /* 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  11595:   fflush(ficlog);
1.190     brouard  11596:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11597:   if(model[0]=='#'){
1.279     brouard  11598:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11599:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11600:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11601:     if(mle != -1){
1.279     brouard  11602:       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  11603:       exit(1);
                   11604:     }
                   11605:   }
1.126     brouard  11606:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11607:     ungetc(c,ficpar);
                   11608:     fgets(line, MAXLINE, ficpar);
                   11609:     numlinepar++;
1.195     brouard  11610:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11611:       z[0]=line[1];
                   11612:     }
                   11613:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11614:     fputs(line, stdout);
                   11615:     //puts(line);
1.126     brouard  11616:     fputs(line,ficparo);
                   11617:     fputs(line,ficlog);
                   11618:   }
                   11619:   ungetc(c,ficpar);
                   11620: 
                   11621:    
1.290     brouard  11622:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11623:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11624:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11625:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11626:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11627:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11628:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11629:   */
                   11630:   if (strlen(model)>1) 
1.187     brouard  11631:     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  11632:   else
1.187     brouard  11633:     ncovmodel=2; /* Constant and age */
1.133     brouard  11634:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11635:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11636:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11637:     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);
                   11638:     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);
                   11639:     fflush(stdout);
                   11640:     fclose (ficlog);
                   11641:     goto end;
                   11642:   }
1.126     brouard  11643:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11644:   delti=delti3[1][1];
                   11645:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11646:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11647: /* We could also provide initial parameters values giving by simple logistic regression 
                   11648:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11649:       /* for(i=1;i<nlstate;i++){ */
                   11650:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11651:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11652:       /* } */
1.126     brouard  11653:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11654:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11655:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11656:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11657:     fclose (ficparo);
                   11658:     fclose (ficlog);
                   11659:     goto end;
                   11660:     exit(0);
1.220     brouard  11661:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11662:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11663:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11664:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11665:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11666:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11667:     hess=matrix(1,npar,1,npar);
1.220     brouard  11668:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11669:     /* Read guessed parameters */
1.126     brouard  11670:     /* Reads comments: lines beginning with '#' */
                   11671:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11672:       ungetc(c,ficpar);
                   11673:       fgets(line, MAXLINE, ficpar);
                   11674:       numlinepar++;
1.141     brouard  11675:       fputs(line,stdout);
1.126     brouard  11676:       fputs(line,ficparo);
                   11677:       fputs(line,ficlog);
                   11678:     }
                   11679:     ungetc(c,ficpar);
                   11680:     
                   11681:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11682:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11683:     for(i=1; i <=nlstate; i++){
1.234     brouard  11684:       j=0;
1.126     brouard  11685:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11686:        if(jj==i) continue;
                   11687:        j++;
1.292     brouard  11688:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11689:          ungetc(c,ficpar);
                   11690:          fgets(line, MAXLINE, ficpar);
                   11691:          numlinepar++;
                   11692:          fputs(line,stdout);
                   11693:          fputs(line,ficparo);
                   11694:          fputs(line,ficlog);
                   11695:        }
                   11696:        ungetc(c,ficpar);
1.234     brouard  11697:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11698:        if ((i1 != i) || (j1 != jj)){
                   11699:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11700: It might be a problem of design; if ncovcol and the model are correct\n \
                   11701: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11702:          exit(1);
                   11703:        }
                   11704:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11705:        if(mle==1)
                   11706:          printf("%1d%1d",i,jj);
                   11707:        fprintf(ficlog,"%1d%1d",i,jj);
                   11708:        for(k=1; k<=ncovmodel;k++){
                   11709:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11710:          if(mle==1){
                   11711:            printf(" %lf",param[i][j][k]);
                   11712:            fprintf(ficlog," %lf",param[i][j][k]);
                   11713:          }
                   11714:          else
                   11715:            fprintf(ficlog," %lf",param[i][j][k]);
                   11716:          fprintf(ficparo," %lf",param[i][j][k]);
                   11717:        }
                   11718:        fscanf(ficpar,"\n");
                   11719:        numlinepar++;
                   11720:        if(mle==1)
                   11721:          printf("\n");
                   11722:        fprintf(ficlog,"\n");
                   11723:        fprintf(ficparo,"\n");
1.126     brouard  11724:       }
                   11725:     }  
                   11726:     fflush(ficlog);
1.234     brouard  11727:     
1.251     brouard  11728:     /* Reads parameters values */
1.126     brouard  11729:     p=param[1][1];
1.251     brouard  11730:     pstart=paramstart[1][1];
1.126     brouard  11731:     
                   11732:     /* Reads comments: lines beginning with '#' */
                   11733:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11734:       ungetc(c,ficpar);
                   11735:       fgets(line, MAXLINE, ficpar);
                   11736:       numlinepar++;
1.141     brouard  11737:       fputs(line,stdout);
1.126     brouard  11738:       fputs(line,ficparo);
                   11739:       fputs(line,ficlog);
                   11740:     }
                   11741:     ungetc(c,ficpar);
                   11742: 
                   11743:     for(i=1; i <=nlstate; i++){
                   11744:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11745:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11746:        if ( (i1-i) * (j1-j) != 0){
                   11747:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11748:          exit(1);
                   11749:        }
                   11750:        printf("%1d%1d",i,j);
                   11751:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11752:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11753:        for(k=1; k<=ncovmodel;k++){
                   11754:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11755:          printf(" %le",delti3[i][j][k]);
                   11756:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11757:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11758:        }
                   11759:        fscanf(ficpar,"\n");
                   11760:        numlinepar++;
                   11761:        printf("\n");
                   11762:        fprintf(ficparo,"\n");
                   11763:        fprintf(ficlog,"\n");
1.126     brouard  11764:       }
                   11765:     }
                   11766:     fflush(ficlog);
1.234     brouard  11767:     
1.145     brouard  11768:     /* Reads covariance matrix */
1.126     brouard  11769:     delti=delti3[1][1];
1.220     brouard  11770:                
                   11771:                
1.126     brouard  11772:     /* 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  11773:                
1.126     brouard  11774:     /* Reads comments: lines beginning with '#' */
                   11775:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11776:       ungetc(c,ficpar);
                   11777:       fgets(line, MAXLINE, ficpar);
                   11778:       numlinepar++;
1.141     brouard  11779:       fputs(line,stdout);
1.126     brouard  11780:       fputs(line,ficparo);
                   11781:       fputs(line,ficlog);
                   11782:     }
                   11783:     ungetc(c,ficpar);
1.220     brouard  11784:                
1.126     brouard  11785:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11786:     hess=matrix(1,npar,1,npar);
1.131     brouard  11787:     for(i=1; i <=npar; i++)
                   11788:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11789:                
1.194     brouard  11790:     /* Scans npar lines */
1.126     brouard  11791:     for(i=1; i <=npar; i++){
1.226     brouard  11792:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11793:       if(count != 3){
1.226     brouard  11794:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11795: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11796: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11797:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11798: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11799: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11800:        exit(1);
1.220     brouard  11801:       }else{
1.226     brouard  11802:        if(mle==1)
                   11803:          printf("%1d%1d%d",i1,j1,jk);
                   11804:       }
                   11805:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11806:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11807:       for(j=1; j <=i; j++){
1.226     brouard  11808:        fscanf(ficpar," %le",&matcov[i][j]);
                   11809:        if(mle==1){
                   11810:          printf(" %.5le",matcov[i][j]);
                   11811:        }
                   11812:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11813:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11814:       }
                   11815:       fscanf(ficpar,"\n");
                   11816:       numlinepar++;
                   11817:       if(mle==1)
1.220     brouard  11818:                                printf("\n");
1.126     brouard  11819:       fprintf(ficlog,"\n");
                   11820:       fprintf(ficparo,"\n");
                   11821:     }
1.194     brouard  11822:     /* End of read covariance matrix npar lines */
1.126     brouard  11823:     for(i=1; i <=npar; i++)
                   11824:       for(j=i+1;j<=npar;j++)
1.226     brouard  11825:        matcov[i][j]=matcov[j][i];
1.126     brouard  11826:     
                   11827:     if(mle==1)
                   11828:       printf("\n");
                   11829:     fprintf(ficlog,"\n");
                   11830:     
                   11831:     fflush(ficlog);
                   11832:     
                   11833:   }    /* End of mle != -3 */
1.218     brouard  11834:   
1.186     brouard  11835:   /*  Main data
                   11836:    */
1.290     brouard  11837:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11838:   /* num=lvector(1,n); */
                   11839:   /* moisnais=vector(1,n); */
                   11840:   /* annais=vector(1,n); */
                   11841:   /* moisdc=vector(1,n); */
                   11842:   /* andc=vector(1,n); */
                   11843:   /* weight=vector(1,n); */
                   11844:   /* agedc=vector(1,n); */
                   11845:   /* cod=ivector(1,n); */
                   11846:   /* for(i=1;i<=n;i++){ */
                   11847:   num=lvector(firstobs,lastobs);
                   11848:   moisnais=vector(firstobs,lastobs);
                   11849:   annais=vector(firstobs,lastobs);
                   11850:   moisdc=vector(firstobs,lastobs);
                   11851:   andc=vector(firstobs,lastobs);
                   11852:   weight=vector(firstobs,lastobs);
                   11853:   agedc=vector(firstobs,lastobs);
                   11854:   cod=ivector(firstobs,lastobs);
                   11855:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11856:     num[i]=0;
                   11857:     moisnais[i]=0;
                   11858:     annais[i]=0;
                   11859:     moisdc[i]=0;
                   11860:     andc[i]=0;
                   11861:     agedc[i]=0;
                   11862:     cod[i]=0;
                   11863:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11864:   }
1.290     brouard  11865:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11866:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11867:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11868:   tab=ivector(1,NCOVMAX);
1.144     brouard  11869:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11870:   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  11871: 
1.136     brouard  11872:   /* Reads data from file datafile */
                   11873:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11874:     goto end;
                   11875: 
                   11876:   /* Calculation of the number of parameters from char model */
1.234     brouard  11877:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11878:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11879:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11880:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11881:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11882:   */
                   11883:   
                   11884:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11885:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11886:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11887:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11888:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11889:   TvarF=ivector(1,NCOVMAX); /*  */
                   11890:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11891:   TvarV=ivector(1,NCOVMAX); /*  */
                   11892:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11893:   TvarA=ivector(1,NCOVMAX); /*  */
                   11894:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11895:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11896:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11897:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11898:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11899:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11900:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11901:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11902:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11903: 
1.230     brouard  11904:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11905:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11906:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11907:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11908:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11909:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11910:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11911:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11912:   */
                   11913:   /* For model-covariate k tells which data-covariate to use but
                   11914:     because this model-covariate is a construction we invent a new column
                   11915:     ncovcol + k1
                   11916:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11917:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11918:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11919:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11920:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11921:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11922:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11923:   */
1.145     brouard  11924:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11925:   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  11926:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11927:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11928:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11929:                         4 covariates (3 plus signs)
                   11930:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11931:                      */  
1.230     brouard  11932:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11933:                                * individual dummy, fixed or varying:
                   11934:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11935:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11936:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11937:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11938:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11939:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11940:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11941:                                * individual quantitative, fixed or varying:
                   11942:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11943:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11944:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11945: /* Main decodemodel */
                   11946: 
1.187     brouard  11947: 
1.223     brouard  11948:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11949:     goto end;
                   11950: 
1.137     brouard  11951:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11952:     nbwarn++;
                   11953:     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); 
                   11954:     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); 
                   11955:   }
1.136     brouard  11956:     /*  if(mle==1){*/
1.137     brouard  11957:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11958:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11959:   }
                   11960: 
                   11961:     /*-calculation of age at interview from date of interview and age at death -*/
                   11962:   agev=matrix(1,maxwav,1,imx);
                   11963: 
                   11964:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11965:     goto end;
                   11966: 
1.126     brouard  11967: 
1.136     brouard  11968:   agegomp=(int)agemin;
1.290     brouard  11969:   free_vector(moisnais,firstobs,lastobs);
                   11970:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11971:   /* free_matrix(mint,1,maxwav,1,n);
                   11972:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11973:   /* free_vector(moisdc,1,n); */
                   11974:   /* free_vector(andc,1,n); */
1.145     brouard  11975:   /* */
                   11976:   
1.126     brouard  11977:   wav=ivector(1,imx);
1.214     brouard  11978:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11979:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11980:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11981:   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.*/
                   11982:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11983:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11984:    
                   11985:   /* Concatenates waves */
1.214     brouard  11986:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11987:      Death is a valid wave (if date is known).
                   11988:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11989:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11990:      and mw[mi+1][i]. dh depends on stepm.
                   11991:   */
                   11992: 
1.126     brouard  11993:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11994:   /* Concatenates waves */
1.145     brouard  11995:  
1.290     brouard  11996:   free_vector(moisdc,firstobs,lastobs);
                   11997:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11998: 
1.126     brouard  11999:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12000:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12001:   ncodemax[1]=1;
1.145     brouard  12002:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12003:   cptcoveff=0;
1.220     brouard  12004:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12005:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12006:   }
                   12007:   
                   12008:   ncovcombmax=pow(2,cptcoveff);
                   12009:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12010:   for(i=1;i<ncovcombmax;i++)
                   12011:     invalidvarcomb[i]=0;
                   12012:   
1.211     brouard  12013:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12014:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12015:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12016:   
1.200     brouard  12017:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12018:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12019:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12020:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12021:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12022:    * (currently 0 or 1) in the data.
                   12023:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12024:    * corresponding modality (h,j).
                   12025:    */
                   12026: 
1.145     brouard  12027:   h=0;
                   12028:   /*if (cptcovn > 0) */
1.126     brouard  12029:   m=pow(2,cptcoveff);
                   12030:  
1.144     brouard  12031:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12032:           * For k=4 covariates, h goes from 1 to m=2**k
                   12033:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12034:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  12035:           *     h\k   1     2     3     4
1.143     brouard  12036:           *______________________________  
                   12037:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   12038:           *     2     2     1     1     1
                   12039:           *     3 i=2 1     2     1     1
                   12040:           *     4     2     2     1     1
                   12041:           *     5 i=3 1 i=2 1     2     1
                   12042:           *     6     2     1     2     1
                   12043:           *     7 i=4 1     2     2     1
                   12044:           *     8     2     2     2     1
1.197     brouard  12045:           *     9 i=5 1 i=3 1 i=2 1     2
                   12046:           *    10     2     1     1     2
                   12047:           *    11 i=6 1     2     1     2
                   12048:           *    12     2     2     1     2
                   12049:           *    13 i=7 1 i=4 1     2     2    
                   12050:           *    14     2     1     2     2
                   12051:           *    15 i=8 1     2     2     2
                   12052:           *    16     2     2     2     2
1.143     brouard  12053:           */
1.212     brouard  12054:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12055:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12056:      * and the value of each covariate?
                   12057:      * V1=1, V2=1, V3=2, V4=1 ?
                   12058:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12059:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12060:      * In order to get the real value in the data, we use nbcode
                   12061:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12062:      * We are keeping this crazy system in order to be able (in the future?) 
                   12063:      * to have more than 2 values (0 or 1) for a covariate.
                   12064:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12065:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12066:      *              bbbbbbbb
                   12067:      *              76543210     
                   12068:      *   h-1        00000101 (6-1=5)
1.219     brouard  12069:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12070:      *           &
                   12071:      *     1        00000001 (1)
1.219     brouard  12072:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12073:      *          +1= 00000001 =1 
1.211     brouard  12074:      *
                   12075:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12076:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12077:      *    >>k'            11
                   12078:      *          &   00000001
                   12079:      *            = 00000001
                   12080:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12081:      * Reverse h=6 and m=16?
                   12082:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12083:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12084:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12085:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12086:      * V3=decodtabm(14,3,2**4)=2
                   12087:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12088:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12089:      *          &1 000000001
                   12090:      *           = 000000001
                   12091:      *         +1= 000000010 =2
                   12092:      *                  2211
                   12093:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12094:      *                  V3=2
1.220     brouard  12095:                 * codtabm and decodtabm are identical
1.211     brouard  12096:      */
                   12097: 
1.145     brouard  12098: 
                   12099:  free_ivector(Ndum,-1,NCOVMAX);
                   12100: 
                   12101: 
1.126     brouard  12102:     
1.186     brouard  12103:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12104:   strcpy(optionfilegnuplot,optionfilefiname);
                   12105:   if(mle==-3)
1.201     brouard  12106:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12107:   strcat(optionfilegnuplot,".gp");
                   12108: 
                   12109:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12110:     printf("Problem with file %s",optionfilegnuplot);
                   12111:   }
                   12112:   else{
1.204     brouard  12113:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12114:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12115:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12116:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12117:   }
                   12118:   /*  fclose(ficgp);*/
1.186     brouard  12119: 
                   12120: 
                   12121:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12122: 
                   12123:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12124:   if(mle==-3)
1.201     brouard  12125:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12126:   strcat(optionfilehtm,".htm");
                   12127:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12128:     printf("Problem with %s \n",optionfilehtm);
                   12129:     exit(0);
1.126     brouard  12130:   }
                   12131: 
                   12132:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12133:   strcat(optionfilehtmcov,"-cov.htm");
                   12134:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12135:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12136:   }
                   12137:   else{
                   12138:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12139: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12140: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12141:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12142:   }
                   12143: 
1.213     brouard  12144:   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-2016-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  12145: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12146: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12147: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12148: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12149: \n\
                   12150: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12151:  <ul><li><h4>Parameter files</h4>\n\
                   12152:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12153:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12154:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12155:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12156:  - Date and time at start: %s</ul>\n",\
                   12157:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12158:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12159:          fileres,fileres,\
                   12160:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12161:   fflush(fichtm);
                   12162: 
                   12163:   strcpy(pathr,path);
                   12164:   strcat(pathr,optionfilefiname);
1.184     brouard  12165: #ifdef WIN32
                   12166:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12167: #else
1.126     brouard  12168:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12169: #endif
                   12170:          
1.126     brouard  12171:   
1.220     brouard  12172:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12173:                 and for any valid combination of covariates
1.126     brouard  12174:      and prints on file fileres'p'. */
1.251     brouard  12175:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12176:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12177: 
                   12178:   fprintf(fichtm,"\n");
1.286     brouard  12179:   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  12180:          ftol, stepm);
                   12181:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12182:   ncurrv=1;
                   12183:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12184:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12185:   ncurrv=i;
                   12186:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12187:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12188:   ncurrv=i;
                   12189:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12190:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12191:   ncurrv=i;
                   12192:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12193:   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", \
                   12194:           nlstate, ndeath, maxwav, mle, weightopt);
                   12195: 
                   12196:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12197: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12198: 
                   12199:   
1.317     brouard  12200:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12201: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12202: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12203:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12204:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12205:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12206:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12207:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12208:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12209: 
1.126     brouard  12210:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12211:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12212:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12213: 
                   12214:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12215:   /* For mortality only */
1.126     brouard  12216:   if (mle==-3){
1.136     brouard  12217:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12218:     for(i=1;i<=NDIM;i++)
                   12219:       for(j=1;j<=NDIM;j++)
                   12220:        ximort[i][j]=0.;
1.186     brouard  12221:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12222:     cens=ivector(firstobs,lastobs);
                   12223:     ageexmed=vector(firstobs,lastobs);
                   12224:     agecens=vector(firstobs,lastobs);
                   12225:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12226:                
1.126     brouard  12227:     for (i=1; i<=imx; i++){
                   12228:       dcwave[i]=-1;
                   12229:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12230:        if (s[m][i]>nlstate) {
                   12231:          dcwave[i]=m;
                   12232:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12233:          break;
                   12234:        }
1.126     brouard  12235:     }
1.226     brouard  12236:     
1.126     brouard  12237:     for (i=1; i<=imx; i++) {
                   12238:       if (wav[i]>0){
1.226     brouard  12239:        ageexmed[i]=agev[mw[1][i]][i];
                   12240:        j=wav[i];
                   12241:        agecens[i]=1.; 
                   12242:        
                   12243:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12244:          agecens[i]=agev[mw[j][i]][i];
                   12245:          cens[i]= 1;
                   12246:        }else if (ageexmed[i]< 1) 
                   12247:          cens[i]= -1;
                   12248:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12249:          cens[i]=0 ;
1.126     brouard  12250:       }
                   12251:       else cens[i]=-1;
                   12252:     }
                   12253:     
                   12254:     for (i=1;i<=NDIM;i++) {
                   12255:       for (j=1;j<=NDIM;j++)
1.226     brouard  12256:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12257:     }
                   12258:     
1.302     brouard  12259:     p[1]=0.0268; p[NDIM]=0.083;
                   12260:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12261:     
                   12262:     
1.136     brouard  12263: #ifdef GSL
                   12264:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12265: #else
1.126     brouard  12266:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12267: #endif
1.201     brouard  12268:     strcpy(filerespow,"POW-MORT_"); 
                   12269:     strcat(filerespow,fileresu);
1.126     brouard  12270:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12271:       printf("Problem with resultfile: %s\n", filerespow);
                   12272:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12273:     }
1.136     brouard  12274: #ifdef GSL
                   12275:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12276: #else
1.126     brouard  12277:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12278: #endif
1.126     brouard  12279:     /*  for (i=1;i<=nlstate;i++)
                   12280:        for(j=1;j<=nlstate+ndeath;j++)
                   12281:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12282:     */
                   12283:     fprintf(ficrespow,"\n");
1.136     brouard  12284: #ifdef GSL
                   12285:     /* gsl starts here */ 
                   12286:     T = gsl_multimin_fminimizer_nmsimplex;
                   12287:     gsl_multimin_fminimizer *sfm = NULL;
                   12288:     gsl_vector *ss, *x;
                   12289:     gsl_multimin_function minex_func;
                   12290: 
                   12291:     /* Initial vertex size vector */
                   12292:     ss = gsl_vector_alloc (NDIM);
                   12293:     
                   12294:     if (ss == NULL){
                   12295:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12296:     }
                   12297:     /* Set all step sizes to 1 */
                   12298:     gsl_vector_set_all (ss, 0.001);
                   12299: 
                   12300:     /* Starting point */
1.126     brouard  12301:     
1.136     brouard  12302:     x = gsl_vector_alloc (NDIM);
                   12303:     
                   12304:     if (x == NULL){
                   12305:       gsl_vector_free(ss);
                   12306:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12307:     }
                   12308:   
                   12309:     /* Initialize method and iterate */
                   12310:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12311:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12312:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12313:     gsl_vector_set(x, 0, p[1]);
                   12314:     gsl_vector_set(x, 1, p[2]);
                   12315: 
                   12316:     minex_func.f = &gompertz_f;
                   12317:     minex_func.n = NDIM;
                   12318:     minex_func.params = (void *)&p; /* ??? */
                   12319:     
                   12320:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12321:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12322:     
                   12323:     printf("Iterations beginning .....\n\n");
                   12324:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12325: 
                   12326:     iteri=0;
                   12327:     while (rval == GSL_CONTINUE){
                   12328:       iteri++;
                   12329:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12330:       
                   12331:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12332:       fflush(0);
                   12333:       
                   12334:       if (status) 
                   12335:         break;
                   12336:       
                   12337:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12338:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12339:       
                   12340:       if (rval == GSL_SUCCESS)
                   12341:         printf ("converged to a local maximum at\n");
                   12342:       
                   12343:       printf("%5d ", iteri);
                   12344:       for (it = 0; it < NDIM; it++){
                   12345:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12346:       }
                   12347:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12348:     }
                   12349:     
                   12350:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12351:     
                   12352:     gsl_vector_free(x); /* initial values */
                   12353:     gsl_vector_free(ss); /* inital step size */
                   12354:     for (it=0; it<NDIM; it++){
                   12355:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12356:       fprintf(ficrespow," %.12lf", p[it]);
                   12357:     }
                   12358:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12359: #endif
                   12360: #ifdef POWELL
                   12361:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12362: #endif  
1.126     brouard  12363:     fclose(ficrespow);
                   12364:     
1.203     brouard  12365:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12366: 
                   12367:     for(i=1; i <=NDIM; i++)
                   12368:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12369:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12370:     
                   12371:     printf("\nCovariance matrix\n ");
1.203     brouard  12372:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12373:     for(i=1; i <=NDIM; i++) {
                   12374:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12375:                                printf("%f ",matcov[i][j]);
                   12376:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12377:       }
1.203     brouard  12378:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12379:     }
                   12380:     
                   12381:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12382:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12383:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12384:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12385:     }
1.302     brouard  12386:     lsurv=vector(agegomp,AGESUP);
                   12387:     lpop=vector(agegomp,AGESUP);
                   12388:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12389:     lsurv[agegomp]=100000;
                   12390:     
                   12391:     for (k=agegomp;k<=AGESUP;k++) {
                   12392:       agemortsup=k;
                   12393:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12394:     }
                   12395:     
                   12396:     for (k=agegomp;k<agemortsup;k++)
                   12397:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12398:     
                   12399:     for (k=agegomp;k<agemortsup;k++){
                   12400:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12401:       sumlpop=sumlpop+lpop[k];
                   12402:     }
                   12403:     
                   12404:     tpop[agegomp]=sumlpop;
                   12405:     for (k=agegomp;k<(agemortsup-3);k++){
                   12406:       /*  tpop[k+1]=2;*/
                   12407:       tpop[k+1]=tpop[k]-lpop[k];
                   12408:     }
                   12409:     
                   12410:     
                   12411:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12412:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12413:       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]);
                   12414:     
                   12415:     
                   12416:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12417:                ageminpar=50;
                   12418:                agemaxpar=100;
1.194     brouard  12419:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12420:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12421: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12422: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12423:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12424: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12425: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12426:     }else{
                   12427:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12428:                        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  12429:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12430:                }
1.201     brouard  12431:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12432:                     stepm, weightopt,\
                   12433:                     model,imx,p,matcov,agemortsup);
                   12434:     
1.302     brouard  12435:     free_vector(lsurv,agegomp,AGESUP);
                   12436:     free_vector(lpop,agegomp,AGESUP);
                   12437:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12438:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12439:     free_ivector(dcwave,firstobs,lastobs);
                   12440:     free_vector(agecens,firstobs,lastobs);
                   12441:     free_vector(ageexmed,firstobs,lastobs);
                   12442:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12443: #ifdef GSL
1.136     brouard  12444: #endif
1.186     brouard  12445:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12446:   /* Standard  */
                   12447:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12448:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12449:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12450:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12451:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12452:     for (k=1; k<=npar;k++)
                   12453:       printf(" %d %8.5f",k,p[k]);
                   12454:     printf("\n");
1.205     brouard  12455:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12456:       /* mlikeli uses func not funcone */
1.247     brouard  12457:       /* for(i=1;i<nlstate;i++){ */
                   12458:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12459:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12460:       /* } */
1.205     brouard  12461:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12462:     }
                   12463:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12464:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12465:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12466:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12467:     }
                   12468:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12469:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12470:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12471:     for (k=1; k<=npar;k++)
                   12472:       printf(" %d %8.5f",k,p[k]);
                   12473:     printf("\n");
                   12474:     
                   12475:     /*--------- results files --------------*/
1.283     brouard  12476:     /* 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  12477:     
                   12478:     
                   12479:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12480:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  12481:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12482: 
                   12483:     printf("#model=  1      +     age ");
                   12484:     fprintf(ficres,"#model=  1      +     age ");
                   12485:     fprintf(ficlog,"#model=  1      +     age ");
                   12486:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   12487: </ul>", model);
                   12488: 
                   12489:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   12490:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12491:     if(nagesqr==1){
                   12492:       printf("  + age*age  ");
                   12493:       fprintf(ficres,"  + age*age  ");
                   12494:       fprintf(ficlog,"  + age*age  ");
                   12495:       fprintf(fichtm, "<th>+ age*age</th>");
                   12496:     }
                   12497:     for(j=1;j <=ncovmodel-2;j++){
                   12498:       if(Typevar[j]==0) {
                   12499:        printf("  +      V%d  ",Tvar[j]);
                   12500:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   12501:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   12502:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12503:       }else if(Typevar[j]==1) {
                   12504:        printf("  +    V%d*age ",Tvar[j]);
                   12505:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   12506:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   12507:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12508:       }else if(Typevar[j]==2) {
                   12509:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12510:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12511:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12512:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12513:       }
                   12514:     }
                   12515:     printf("\n");
                   12516:     fprintf(ficres,"\n");
                   12517:     fprintf(ficlog,"\n");
                   12518:     fprintf(fichtm, "</tr>");
                   12519:     fprintf(fichtm, "\n");
                   12520:     
                   12521:     
1.126     brouard  12522:     for(i=1,jk=1; i <=nlstate; i++){
                   12523:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12524:        if (k != i) {
1.319     brouard  12525:          fprintf(fichtm, "<tr>");
1.225     brouard  12526:          printf("%d%d ",i,k);
                   12527:          fprintf(ficlog,"%d%d ",i,k);
                   12528:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  12529:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12530:          for(j=1; j <=ncovmodel; j++){
                   12531:            printf("%12.7f ",p[jk]);
                   12532:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12533:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  12534:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  12535:            jk++; 
                   12536:          }
                   12537:          printf("\n");
                   12538:          fprintf(ficlog,"\n");
                   12539:          fprintf(ficres,"\n");
1.319     brouard  12540:          fprintf(fichtm, "</tr>\n");
1.225     brouard  12541:        }
1.126     brouard  12542:       }
                   12543:     }
1.319     brouard  12544:     /* fprintf(fichtm,"</tr>\n"); */
                   12545:     fprintf(fichtm,"</table>\n");
                   12546:     fprintf(fichtm, "\n");
                   12547: 
1.203     brouard  12548:     if(mle != 0){
                   12549:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12550:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12551:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12552:       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");
                   12553:       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.321   ! brouard  12554:       fprintf(fichtm, "\n<p>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 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n</br>");
1.319     brouard  12555:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   12556:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12557:       if(nagesqr==1){
                   12558:        printf("  + age*age  ");
                   12559:        fprintf(ficres,"  + age*age  ");
                   12560:        fprintf(ficlog,"  + age*age  ");
                   12561:        fprintf(fichtm, "<th>+ age*age</th>");
                   12562:       }
                   12563:       for(j=1;j <=ncovmodel-2;j++){
                   12564:        if(Typevar[j]==0) {
                   12565:          printf("  +      V%d  ",Tvar[j]);
                   12566:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12567:        }else if(Typevar[j]==1) {
                   12568:          printf("  +    V%d*age ",Tvar[j]);
                   12569:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12570:        }else if(Typevar[j]==2) {
                   12571:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12572:        }
                   12573:       }
                   12574:       fprintf(fichtm, "</tr>\n");
                   12575:  
1.203     brouard  12576:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12577:        for(k=1; k <=(nlstate+ndeath); k++){
                   12578:          if (k != i) {
1.319     brouard  12579:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  12580:            printf("%d%d ",i,k);
                   12581:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  12582:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12583:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  12584:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.321   ! brouard  12585:              printf("%12.7f(%12.7f) sqrt(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]));
        !          12586:              fprintf(ficlog,"%12.7f(%12.7f) sqrt(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  12587:              if(fabs(wald) > 1.96){
1.321   ! brouard  12588:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  12589:              }else{
                   12590:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   12591:              }
1.321   ! brouard  12592:              fprintf(fichtm,"sqrt(W)=%8.3f</br>",wald);
1.319     brouard  12593:              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  12594:              jk++; 
                   12595:            }
                   12596:            printf("\n");
                   12597:            fprintf(ficlog,"\n");
1.319     brouard  12598:            fprintf(fichtm, "</tr>\n");
1.225     brouard  12599:          }
                   12600:        }
1.193     brouard  12601:       }
1.203     brouard  12602:     } /* end of hesscov and Wald tests */
1.319     brouard  12603:     fprintf(fichtm,"</table>\n");
1.225     brouard  12604:     
1.203     brouard  12605:     /*  */
1.126     brouard  12606:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12607:     printf("# Scales (for hessian or gradient estimation)\n");
                   12608:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12609:     for(i=1,jk=1; i <=nlstate; i++){
                   12610:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12611:        if (j!=i) {
                   12612:          fprintf(ficres,"%1d%1d",i,j);
                   12613:          printf("%1d%1d",i,j);
                   12614:          fprintf(ficlog,"%1d%1d",i,j);
                   12615:          for(k=1; k<=ncovmodel;k++){
                   12616:            printf(" %.5e",delti[jk]);
                   12617:            fprintf(ficlog," %.5e",delti[jk]);
                   12618:            fprintf(ficres," %.5e",delti[jk]);
                   12619:            jk++;
                   12620:          }
                   12621:          printf("\n");
                   12622:          fprintf(ficlog,"\n");
                   12623:          fprintf(ficres,"\n");
                   12624:        }
1.126     brouard  12625:       }
                   12626:     }
                   12627:     
                   12628:     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  12629:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12630:       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");
                   12631:     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");
                   12632:     /* # 121 Var(a12)\n\ */
                   12633:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12634:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12635:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12636:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12637:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12638:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12639:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12640:     
                   12641:     
                   12642:     /* Just to have a covariance matrix which will be more understandable
                   12643:        even is we still don't want to manage dictionary of variables
                   12644:     */
                   12645:     for(itimes=1;itimes<=2;itimes++){
                   12646:       jj=0;
                   12647:       for(i=1; i <=nlstate; i++){
1.225     brouard  12648:        for(j=1; j <=nlstate+ndeath; j++){
                   12649:          if(j==i) continue;
                   12650:          for(k=1; k<=ncovmodel;k++){
                   12651:            jj++;
                   12652:            ca[0]= k+'a'-1;ca[1]='\0';
                   12653:            if(itimes==1){
                   12654:              if(mle>=1)
                   12655:                printf("#%1d%1d%d",i,j,k);
                   12656:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12657:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12658:            }else{
                   12659:              if(mle>=1)
                   12660:                printf("%1d%1d%d",i,j,k);
                   12661:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12662:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12663:            }
                   12664:            ll=0;
                   12665:            for(li=1;li <=nlstate; li++){
                   12666:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12667:                if(lj==li) continue;
                   12668:                for(lk=1;lk<=ncovmodel;lk++){
                   12669:                  ll++;
                   12670:                  if(ll<=jj){
                   12671:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12672:                    if(ll<jj){
                   12673:                      if(itimes==1){
                   12674:                        if(mle>=1)
                   12675:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12676:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12677:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12678:                      }else{
                   12679:                        if(mle>=1)
                   12680:                          printf(" %.5e",matcov[jj][ll]); 
                   12681:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12682:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12683:                      }
                   12684:                    }else{
                   12685:                      if(itimes==1){
                   12686:                        if(mle>=1)
                   12687:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12688:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12689:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12690:                      }else{
                   12691:                        if(mle>=1)
                   12692:                          printf(" %.7e",matcov[jj][ll]); 
                   12693:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12694:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12695:                      }
                   12696:                    }
                   12697:                  }
                   12698:                } /* end lk */
                   12699:              } /* end lj */
                   12700:            } /* end li */
                   12701:            if(mle>=1)
                   12702:              printf("\n");
                   12703:            fprintf(ficlog,"\n");
                   12704:            fprintf(ficres,"\n");
                   12705:            numlinepar++;
                   12706:          } /* end k*/
                   12707:        } /*end j */
1.126     brouard  12708:       } /* end i */
                   12709:     } /* end itimes */
                   12710:     
                   12711:     fflush(ficlog);
                   12712:     fflush(ficres);
1.225     brouard  12713:     while(fgets(line, MAXLINE, ficpar)) {
                   12714:       /* If line starts with a # it is a comment */
                   12715:       if (line[0] == '#') {
                   12716:        numlinepar++;
                   12717:        fputs(line,stdout);
                   12718:        fputs(line,ficparo);
                   12719:        fputs(line,ficlog);
1.299     brouard  12720:        fputs(line,ficres);
1.225     brouard  12721:        continue;
                   12722:       }else
                   12723:        break;
                   12724:     }
                   12725:     
1.209     brouard  12726:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12727:     /*   ungetc(c,ficpar); */
                   12728:     /*   fgets(line, MAXLINE, ficpar); */
                   12729:     /*   fputs(line,stdout); */
                   12730:     /*   fputs(line,ficparo); */
                   12731:     /* } */
                   12732:     /* ungetc(c,ficpar); */
1.126     brouard  12733:     
                   12734:     estepm=0;
1.209     brouard  12735:     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  12736:       
                   12737:       if (num_filled != 6) {
                   12738:        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);
                   12739:        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);
                   12740:        goto end;
                   12741:       }
                   12742:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12743:     }
                   12744:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12745:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12746:     
1.209     brouard  12747:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12748:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12749:     if (fage <= 2) {
                   12750:       bage = ageminpar;
                   12751:       fage = agemaxpar;
                   12752:     }
                   12753:     
                   12754:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12755:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12756:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12757:                
1.186     brouard  12758:     /* Other stuffs, more or less useful */    
1.254     brouard  12759:     while(fgets(line, MAXLINE, ficpar)) {
                   12760:       /* If line starts with a # it is a comment */
                   12761:       if (line[0] == '#') {
                   12762:        numlinepar++;
                   12763:        fputs(line,stdout);
                   12764:        fputs(line,ficparo);
                   12765:        fputs(line,ficlog);
1.299     brouard  12766:        fputs(line,ficres);
1.254     brouard  12767:        continue;
                   12768:       }else
                   12769:        break;
                   12770:     }
                   12771: 
                   12772:     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){
                   12773:       
                   12774:       if (num_filled != 7) {
                   12775:        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);
                   12776:        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);
                   12777:        goto end;
                   12778:       }
                   12779:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12780:       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);
                   12781:       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);
                   12782:       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  12783:     }
1.254     brouard  12784: 
                   12785:     while(fgets(line, MAXLINE, ficpar)) {
                   12786:       /* If line starts with a # it is a comment */
                   12787:       if (line[0] == '#') {
                   12788:        numlinepar++;
                   12789:        fputs(line,stdout);
                   12790:        fputs(line,ficparo);
                   12791:        fputs(line,ficlog);
1.299     brouard  12792:        fputs(line,ficres);
1.254     brouard  12793:        continue;
                   12794:       }else
                   12795:        break;
1.126     brouard  12796:     }
                   12797:     
                   12798:     
                   12799:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12800:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12801:     
1.254     brouard  12802:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12803:       if (num_filled != 1) {
                   12804:        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);
                   12805:        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);
                   12806:        goto end;
                   12807:       }
                   12808:       printf("pop_based=%d\n",popbased);
                   12809:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12810:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12811:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12812:     }
                   12813:      
1.258     brouard  12814:     /* Results */
1.307     brouard  12815:     endishere=0;
1.258     brouard  12816:     nresult=0;
1.308     brouard  12817:     parameterline=0;
1.258     brouard  12818:     do{
                   12819:       if(!fgets(line, MAXLINE, ficpar)){
                   12820:        endishere=1;
1.308     brouard  12821:        parameterline=15;
1.258     brouard  12822:       }else if (line[0] == '#') {
                   12823:        /* If line starts with a # it is a comment */
1.254     brouard  12824:        numlinepar++;
                   12825:        fputs(line,stdout);
                   12826:        fputs(line,ficparo);
                   12827:        fputs(line,ficlog);
1.299     brouard  12828:        fputs(line,ficres);
1.254     brouard  12829:        continue;
1.258     brouard  12830:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12831:        parameterline=11;
1.296     brouard  12832:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12833:        parameterline=12;
1.307     brouard  12834:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  12835:        parameterline=13;
1.307     brouard  12836:       }
1.258     brouard  12837:       else{
                   12838:        parameterline=14;
1.254     brouard  12839:       }
1.308     brouard  12840:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  12841:       case 11:
1.296     brouard  12842:        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)){
                   12843:                  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  12844:          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);
                   12845:          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);
                   12846:          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);
                   12847:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12848:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12849:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12850:           prvforecast = 1;
                   12851:        } 
                   12852:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  12853:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12854:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12855:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12856:           prvforecast = 2;
                   12857:        }
                   12858:        else {
                   12859:          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);
                   12860:          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);
                   12861:          goto end;
1.258     brouard  12862:        }
1.254     brouard  12863:        break;
1.258     brouard  12864:       case 12:
1.296     brouard  12865:        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)){
                   12866:           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);
                   12867:          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);
                   12868:          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);
                   12869:          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);
                   12870:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12871:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12872:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12873:           prvbackcast = 1;
                   12874:        } 
                   12875:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  12876:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12877:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12878:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12879:           prvbackcast = 2;
                   12880:        }
                   12881:        else {
                   12882:          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);
                   12883:          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);
                   12884:          goto end;
1.258     brouard  12885:        }
1.230     brouard  12886:        break;
1.258     brouard  12887:       case 13:
1.307     brouard  12888:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   12889:        nresult++; /* Sum of resultlines */
                   12890:        printf("Result %d: result:%s\n",nresult, resultline);
1.318     brouard  12891:        if(nresult > MAXRESULTLINESPONE-1){
                   12892:          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);
                   12893:          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  12894:          goto end;
                   12895:        }
1.310     brouard  12896:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  12897:          fprintf(ficparo,"result: %s\n",resultline);
                   12898:          fprintf(ficres,"result: %s\n",resultline);
                   12899:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  12900:        } else
                   12901:          goto end;
1.307     brouard  12902:        break;
                   12903:       case 14:
                   12904:        printf("Error: Unknown command '%s'\n",line);
                   12905:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  12906:        if(line[0] == ' ' || line[0] == '\n'){
                   12907:          printf("It should not be an empty line '%s'\n",line);
                   12908:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   12909:        }         
1.307     brouard  12910:        if(ncovmodel >=2 && nresult==0 ){
                   12911:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   12912:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12913:        }
1.307     brouard  12914:        /* goto end; */
                   12915:        break;
1.308     brouard  12916:       case 15:
                   12917:        printf("End of resultlines.\n");
                   12918:        fprintf(ficlog,"End of resultlines.\n");
                   12919:        break;
                   12920:       default: /* parameterline =0 */
1.307     brouard  12921:        nresult=1;
                   12922:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  12923:       } /* End switch parameterline */
                   12924:     }while(endishere==0); /* End do */
1.126     brouard  12925:     
1.230     brouard  12926:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12927:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12928:     
                   12929:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12930:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12931:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12932: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12933: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12934:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12935: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12936: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12937:     }else{
1.270     brouard  12938:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12939:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12940:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12941:       if(prvforecast==1){
                   12942:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12943:         jprojd=jproj1;
                   12944:         mprojd=mproj1;
                   12945:         anprojd=anproj1;
                   12946:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12947:         jprojf=jproj2;
                   12948:         mprojf=mproj2;
                   12949:         anprojf=anproj2;
                   12950:       } else if(prvforecast == 2){
                   12951:         dateprojd=dateintmean;
                   12952:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12953:         dateprojf=dateintmean+yrfproj;
                   12954:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12955:       }
                   12956:       if(prvbackcast==1){
                   12957:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12958:         jbackd=jback1;
                   12959:         mbackd=mback1;
                   12960:         anbackd=anback1;
                   12961:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12962:         jbackf=jback2;
                   12963:         mbackf=mback2;
                   12964:         anbackf=anback2;
                   12965:       } else if(prvbackcast == 2){
                   12966:         datebackd=dateintmean;
                   12967:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12968:         datebackf=dateintmean-yrbproj;
                   12969:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12970:       }
                   12971:       
                   12972:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12973:     }
                   12974:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12975:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12976:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12977:                
1.225     brouard  12978:     /*------------ free_vector  -------------*/
                   12979:     /*  chdir(path); */
1.220     brouard  12980:                
1.215     brouard  12981:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12982:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12983:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12984:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12985:     free_lvector(num,firstobs,lastobs);
                   12986:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12987:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12988:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12989:     fclose(ficparo);
                   12990:     fclose(ficres);
1.220     brouard  12991:                
                   12992:                
1.186     brouard  12993:     /* Other results (useful)*/
1.220     brouard  12994:                
                   12995:                
1.126     brouard  12996:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12997:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12998:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12999:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13000:     fclose(ficrespl);
                   13001: 
                   13002:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13003:     /*#include "hpijx.h"*/
                   13004:     hPijx(p, bage, fage);
1.145     brouard  13005:     fclose(ficrespij);
1.227     brouard  13006:     
1.220     brouard  13007:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  13008:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  13009:     k=1;
1.126     brouard  13010:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13011:     
1.269     brouard  13012:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13013:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13014:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13015:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13016:        for(k=1;k<=ncovcombmax;k++)
                   13017:          probs[i][j][k]=0.;
1.269     brouard  13018:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13019:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13020:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13021:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13022:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13023:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13024:          for(k=1;k<=ncovcombmax;k++)
                   13025:            mobaverages[i][j][k]=0.;
1.219     brouard  13026:       mobaverage=mobaverages;
                   13027:       if (mobilav!=0) {
1.235     brouard  13028:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13029:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13030:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13031:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13032:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13033:        }
1.269     brouard  13034:       } else if (mobilavproj !=0) {
1.235     brouard  13035:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13036:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13037:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13038:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13039:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13040:        }
1.269     brouard  13041:       }else{
                   13042:        printf("Internal error moving average\n");
                   13043:        fflush(stdout);
                   13044:        exit(1);
1.219     brouard  13045:       }
                   13046:     }/* end if moving average */
1.227     brouard  13047:     
1.126     brouard  13048:     /*---------- Forecasting ------------------*/
1.296     brouard  13049:     if(prevfcast==1){ 
                   13050:       /*   /\*    if(stepm ==1){*\/ */
                   13051:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13052:       /*This done previously after freqsummary.*/
                   13053:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13054:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13055:       
                   13056:       /* } else if (prvforecast==2){ */
                   13057:       /*   /\*    if(stepm ==1){*\/ */
                   13058:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13059:       /* } */
                   13060:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13061:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13062:     }
1.269     brouard  13063: 
1.296     brouard  13064:     /* Prevbcasting */
                   13065:     if(prevbcast==1){
1.219     brouard  13066:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13067:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13068:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13069: 
                   13070:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13071: 
                   13072:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13073: 
1.219     brouard  13074:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13075:       fclose(ficresplb);
                   13076: 
1.222     brouard  13077:       hBijx(p, bage, fage, mobaverage);
                   13078:       fclose(ficrespijb);
1.219     brouard  13079: 
1.296     brouard  13080:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13081:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13082:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13083:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13084:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13085:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13086: 
                   13087:       
1.269     brouard  13088:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13089: 
                   13090:       
1.269     brouard  13091:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13092:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13093:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13094:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13095:     }    /* end  Prevbcasting */
1.268     brouard  13096:  
1.186     brouard  13097:  
                   13098:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13099: 
1.215     brouard  13100:     free_ivector(wav,1,imx);
                   13101:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13102:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13103:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13104:                
                   13105:                
1.127     brouard  13106:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13107:                
1.201     brouard  13108:     strcpy(filerese,"E_");
                   13109:     strcat(filerese,fileresu);
1.126     brouard  13110:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13111:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13112:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13113:     }
1.208     brouard  13114:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13115:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13116: 
                   13117:     pstamp(ficreseij);
1.219     brouard  13118:                
1.235     brouard  13119:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13120:     if (cptcovn < 1){i1=1;}
                   13121:     
                   13122:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13123:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13124:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13125:        continue;
1.219     brouard  13126:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13127:       printf("\n#****** ");
1.225     brouard  13128:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  13129:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  13130:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13131:       }
                   13132:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13133:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13134:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  13135:       }
                   13136:       fprintf(ficreseij,"******\n");
1.235     brouard  13137:       printf("******\n");
1.219     brouard  13138:       
                   13139:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13140:       oldm=oldms;savm=savms;
1.235     brouard  13141:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13142:       
1.219     brouard  13143:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13144:     }
                   13145:     fclose(ficreseij);
1.208     brouard  13146:     printf("done evsij\n");fflush(stdout);
                   13147:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13148: 
1.218     brouard  13149:                
1.227     brouard  13150:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13151:                
1.201     brouard  13152:     strcpy(filerest,"T_");
                   13153:     strcat(filerest,fileresu);
1.127     brouard  13154:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13155:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13156:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13157:     }
1.208     brouard  13158:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13159:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13160:     strcpy(fileresstde,"STDE_");
                   13161:     strcat(fileresstde,fileresu);
1.126     brouard  13162:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13163:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13164:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13165:     }
1.227     brouard  13166:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13167:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13168: 
1.201     brouard  13169:     strcpy(filerescve,"CVE_");
                   13170:     strcat(filerescve,fileresu);
1.126     brouard  13171:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13172:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13173:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13174:     }
1.227     brouard  13175:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13176:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13177: 
1.201     brouard  13178:     strcpy(fileresv,"V_");
                   13179:     strcat(fileresv,fileresu);
1.126     brouard  13180:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13181:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13182:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13183:     }
1.227     brouard  13184:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13185:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13186: 
1.235     brouard  13187:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13188:     if (cptcovn < 1){i1=1;}
                   13189:     
                   13190:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13191:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13192:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13193:        continue;
1.321   ! brouard  13194:       printf("\n# model %s \n#****** Result for:", model);
        !          13195:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
        !          13196:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.227     brouard  13197:       for(j=1;j<=cptcoveff;j++){ 
                   13198:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13199:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13200:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13201:       }
1.235     brouard  13202:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13203:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13204:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13205:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13206:       }        
1.208     brouard  13207:       fprintf(ficrest,"******\n");
1.227     brouard  13208:       fprintf(ficlog,"******\n");
                   13209:       printf("******\n");
1.208     brouard  13210:       
                   13211:       fprintf(ficresstdeij,"\n#****** ");
                   13212:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13213:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  13214:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13215:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  13216:       }
1.235     brouard  13217:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13218:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13219:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13220:       }        
1.208     brouard  13221:       fprintf(ficresstdeij,"******\n");
                   13222:       fprintf(ficrescveij,"******\n");
                   13223:       
                   13224:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13225:       /* pstamp(ficresvij); */
1.225     brouard  13226:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  13227:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  13228:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13229:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13230:       }        
1.208     brouard  13231:       fprintf(ficresvij,"******\n");
                   13232:       
                   13233:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13234:       oldm=oldms;savm=savms;
1.235     brouard  13235:       printf(" cvevsij ");
                   13236:       fprintf(ficlog, " cvevsij ");
                   13237:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13238:       printf(" end cvevsij \n ");
                   13239:       fprintf(ficlog, " end cvevsij \n ");
                   13240:       
                   13241:       /*
                   13242:        */
                   13243:       /* goto endfree; */
                   13244:       
                   13245:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13246:       pstamp(ficrest);
                   13247:       
1.269     brouard  13248:       epj=vector(1,nlstate+1);
1.208     brouard  13249:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13250:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13251:        cptcod= 0; /* To be deleted */
                   13252:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13253:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13254:        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  13255:        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 ");
                   13256:        if(vpopbased==1)
                   13257:          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);
                   13258:        else
1.288     brouard  13259:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13260:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13261:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13262:        fprintf(ficrest,"\n");
                   13263:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13264:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13265:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13266:        for(age=bage; age <=fage ;age++){
1.235     brouard  13267:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13268:          if (vpopbased==1) {
                   13269:            if(mobilav ==0){
                   13270:              for(i=1; i<=nlstate;i++)
                   13271:                prlim[i][i]=probs[(int)age][i][k];
                   13272:            }else{ /* mobilav */ 
                   13273:              for(i=1; i<=nlstate;i++)
                   13274:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13275:            }
                   13276:          }
1.219     brouard  13277:          
1.227     brouard  13278:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13279:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13280:          /* printf(" age %4.0f ",age); */
                   13281:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13282:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13283:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13284:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13285:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13286:            }
                   13287:            epj[nlstate+1] +=epj[j];
                   13288:          }
                   13289:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13290:          
1.227     brouard  13291:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13292:            for(j=1;j <=nlstate;j++)
                   13293:              vepp += vareij[i][j][(int)age];
                   13294:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13295:          for(j=1;j <=nlstate;j++){
                   13296:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13297:          }
                   13298:          fprintf(ficrest,"\n");
                   13299:        }
1.208     brouard  13300:       } /* End vpopbased */
1.269     brouard  13301:       free_vector(epj,1,nlstate+1);
1.208     brouard  13302:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13303:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13304:       printf("done selection\n");fflush(stdout);
                   13305:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13306:       
1.235     brouard  13307:     } /* End k selection */
1.227     brouard  13308: 
                   13309:     printf("done State-specific expectancies\n");fflush(stdout);
                   13310:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13311: 
1.288     brouard  13312:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13313:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13314: 
1.227     brouard  13315:     
1.290     brouard  13316:     free_vector(weight,firstobs,lastobs);
1.227     brouard  13317:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13318:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13319:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13320:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13321:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13322:     free_ivector(tab,1,NCOVMAX);
                   13323:     fclose(ficresstdeij);
                   13324:     fclose(ficrescveij);
                   13325:     fclose(ficresvij);
                   13326:     fclose(ficrest);
                   13327:     fclose(ficpar);
                   13328:     
                   13329:     
1.126     brouard  13330:     /*---------- End : free ----------------*/
1.219     brouard  13331:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13332:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13333:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13334:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13335:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13336:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13337:   /* endfree:*/
                   13338:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13339:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13340:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13341:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13342:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13343:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13344:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13345:   free_matrix(matcov,1,npar,1,npar);
                   13346:   free_matrix(hess,1,npar,1,npar);
                   13347:   /*free_vector(delti,1,npar);*/
                   13348:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13349:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13350:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13351:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13352:   
                   13353:   free_ivector(ncodemax,1,NCOVMAX);
                   13354:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13355:   free_ivector(Dummy,-1,NCOVMAX);
                   13356:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13357:   free_ivector(DummyV,1,NCOVMAX);
                   13358:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13359:   free_ivector(Typevar,-1,NCOVMAX);
                   13360:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13361:   free_ivector(TvarsQ,1,NCOVMAX);
                   13362:   free_ivector(TvarsQind,1,NCOVMAX);
                   13363:   free_ivector(TvarsD,1,NCOVMAX);
                   13364:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13365:   free_ivector(TvarFD,1,NCOVMAX);
                   13366:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13367:   free_ivector(TvarF,1,NCOVMAX);
                   13368:   free_ivector(TvarFind,1,NCOVMAX);
                   13369:   free_ivector(TvarV,1,NCOVMAX);
                   13370:   free_ivector(TvarVind,1,NCOVMAX);
                   13371:   free_ivector(TvarA,1,NCOVMAX);
                   13372:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13373:   free_ivector(TvarFQ,1,NCOVMAX);
                   13374:   free_ivector(TvarFQind,1,NCOVMAX);
                   13375:   free_ivector(TvarVD,1,NCOVMAX);
                   13376:   free_ivector(TvarVDind,1,NCOVMAX);
                   13377:   free_ivector(TvarVQ,1,NCOVMAX);
                   13378:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13379:   free_ivector(Tvarsel,1,NCOVMAX);
                   13380:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13381:   free_ivector(Tposprod,1,NCOVMAX);
                   13382:   free_ivector(Tprod,1,NCOVMAX);
                   13383:   free_ivector(Tvaraff,1,NCOVMAX);
                   13384:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13385:   free_ivector(Tage,1,NCOVMAX);
                   13386:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13387:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13388:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13389:   
                   13390:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13391:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13392:   fflush(fichtm);
                   13393:   fflush(ficgp);
                   13394:   
1.227     brouard  13395:   
1.126     brouard  13396:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13397:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13398:     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  13399:   }else{
                   13400:     printf("End of Imach\n");
                   13401:     fprintf(ficlog,"End of Imach\n");
                   13402:   }
                   13403:   printf("See log file on %s\n",filelog);
                   13404:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13405:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13406:   rend_time = time(NULL);  
                   13407:   end_time = *localtime(&rend_time);
                   13408:   /* tml = *localtime(&end_time.tm_sec); */
                   13409:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13410:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13411:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13412:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13413:   
1.157     brouard  13414:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13415:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13416:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13417:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13418: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13419:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13420:   fclose(fichtm);
                   13421:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13422:   fclose(fichtmcov);
                   13423:   fclose(ficgp);
                   13424:   fclose(ficlog);
                   13425:   /*------ End -----------*/
1.227     brouard  13426:   
1.281     brouard  13427: 
                   13428: /* Executes gnuplot */
1.227     brouard  13429:   
                   13430:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13431: #ifdef WIN32
1.227     brouard  13432:   if (_chdir(pathcd) != 0)
                   13433:     printf("Can't move to directory %s!\n",path);
                   13434:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13435: #else
1.227     brouard  13436:     if(chdir(pathcd) != 0)
                   13437:       printf("Can't move to directory %s!\n", path);
                   13438:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13439: #endif 
1.126     brouard  13440:     printf("Current directory %s!\n",pathcd);
                   13441:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13442:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13443: #ifdef _WIN32
1.126     brouard  13444:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13445: #endif
                   13446:   if(!stat(plotcmd,&info)){
1.158     brouard  13447:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13448:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13449:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13450:     }else
                   13451:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13452: #ifdef __unix
1.126     brouard  13453:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13454:     if(!stat(plotcmd,&info)){
1.158     brouard  13455:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13456:     }else
                   13457:       strcpy(pplotcmd,plotcmd);
                   13458: #endif
                   13459:   }else
                   13460:     strcpy(pplotcmd,plotcmd);
                   13461:   
                   13462:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13463:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13464:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13465:   
1.126     brouard  13466:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13467:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13468:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13469:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13470:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13471:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13472:       strcpy(plotcmd,pplotcmd);
                   13473:     }
1.126     brouard  13474:   }
1.158     brouard  13475:   printf(" Successful, please wait...");
1.126     brouard  13476:   while (z[0] != 'q') {
                   13477:     /* chdir(path); */
1.154     brouard  13478:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13479:     scanf("%s",z);
                   13480: /*     if (z[0] == 'c') system("./imach"); */
                   13481:     if (z[0] == 'e') {
1.158     brouard  13482: #ifdef __APPLE__
1.152     brouard  13483:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13484: #elif __linux
                   13485:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13486: #else
1.152     brouard  13487:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13488: #endif
                   13489:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13490:       system(pplotcmd);
1.126     brouard  13491:     }
                   13492:     else if (z[0] == 'g') system(plotcmd);
                   13493:     else if (z[0] == 'q') exit(0);
                   13494:   }
1.227     brouard  13495: end:
1.126     brouard  13496:   while (z[0] != 'q') {
1.195     brouard  13497:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13498:     scanf("%s",z);
                   13499:   }
1.283     brouard  13500:   printf("End\n");
1.282     brouard  13501:   exit(0);
1.126     brouard  13502: }

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