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

1.316   ! brouard     1: /* $Id: imach.c,v 1.315 2022/05/11 15:06:32 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.316   ! brouard     4:   Revision 1.315  2022/05/11 15:06:32  brouard
        !             5:   *** empty log message ***
        !             6: 
1.315     brouard     7:   Revision 1.314  2022/04/13 17:43:09  brouard
                      8:   * imach.c (Module): Adding link to text data files
                      9: 
1.314     brouard    10:   Revision 1.313  2022/04/11 15:57:42  brouard
                     11:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     12: 
1.313     brouard    13:   Revision 1.312  2022/04/05 21:24:39  brouard
                     14:   *** empty log message ***
                     15: 
1.312     brouard    16:   Revision 1.311  2022/04/05 21:03:51  brouard
                     17:   Summary: Fixed quantitative covariates
                     18: 
                     19:          Fixed covariates (dummy or quantitative)
                     20:        with missing values have never been allowed but are ERRORS and
                     21:        program quits. Standard deviations of fixed covariates were
                     22:        wrongly computed. Mean and standard deviations of time varying
                     23:        covariates are still not computed.
                     24: 
1.311     brouard    25:   Revision 1.310  2022/03/17 08:45:53  brouard
                     26:   Summary: 99r25
                     27: 
                     28:   Improving detection of errors: result lines should be compatible with
                     29:   the model.
                     30: 
1.310     brouard    31:   Revision 1.309  2021/05/20 12:39:14  brouard
                     32:   Summary: Version 0.99r24
                     33: 
1.309     brouard    34:   Revision 1.308  2021/03/31 13:11:57  brouard
                     35:   Summary: Version 0.99r23
                     36: 
                     37: 
                     38:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     39: 
1.308     brouard    40:   Revision 1.307  2021/03/08 18:11:32  brouard
                     41:   Summary: 0.99r22 fixed bug on result:
                     42: 
1.307     brouard    43:   Revision 1.306  2021/02/20 15:44:02  brouard
                     44:   Summary: Version 0.99r21
                     45: 
                     46:   * imach.c (Module): Fix bug on quitting after result lines!
                     47:   (Module): Version 0.99r21
                     48: 
1.306     brouard    49:   Revision 1.305  2021/02/20 15:28:30  brouard
                     50:   * imach.c (Module): Fix bug on quitting after result lines!
                     51: 
1.305     brouard    52:   Revision 1.304  2021/02/12 11:34:20  brouard
                     53:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                     54: 
1.304     brouard    55:   Revision 1.303  2021/02/11 19:50:15  brouard
                     56:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                     57: 
1.303     brouard    58:   Revision 1.302  2020/02/22 21:00:05  brouard
                     59:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                     60:   and life table from the data without any state)
                     61: 
1.302     brouard    62:   Revision 1.301  2019/06/04 13:51:20  brouard
                     63:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                     64: 
1.301     brouard    65:   Revision 1.300  2019/05/22 19:09:45  brouard
                     66:   Summary: version 0.99r19 of May 2019
                     67: 
1.300     brouard    68:   Revision 1.299  2019/05/22 18:37:08  brouard
                     69:   Summary: Cleaned 0.99r19
                     70: 
1.299     brouard    71:   Revision 1.298  2019/05/22 18:19:56  brouard
                     72:   *** empty log message ***
                     73: 
1.298     brouard    74:   Revision 1.297  2019/05/22 17:56:10  brouard
                     75:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                     76: 
1.297     brouard    77:   Revision 1.296  2019/05/20 13:03:18  brouard
                     78:   Summary: Projection syntax simplified
                     79: 
                     80: 
                     81:   We can now start projections, forward or backward, from the mean date
                     82:   of inteviews up to or down to a number of years of projection:
                     83:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                     84:   or
                     85:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                     86:   or
                     87:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                     88:   or
                     89:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                     90: 
1.296     brouard    91:   Revision 1.295  2019/05/18 09:52:50  brouard
                     92:   Summary: doxygen tex bug
                     93: 
1.295     brouard    94:   Revision 1.294  2019/05/16 14:54:33  brouard
                     95:   Summary: There was some wrong lines added
                     96: 
1.294     brouard    97:   Revision 1.293  2019/05/09 15:17:34  brouard
                     98:   *** empty log message ***
                     99: 
1.293     brouard   100:   Revision 1.292  2019/05/09 14:17:20  brouard
                    101:   Summary: Some updates
                    102: 
1.292     brouard   103:   Revision 1.291  2019/05/09 13:44:18  brouard
                    104:   Summary: Before ncovmax
                    105: 
1.291     brouard   106:   Revision 1.290  2019/05/09 13:39:37  brouard
                    107:   Summary: 0.99r18 unlimited number of individuals
                    108: 
                    109:   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.
                    110: 
1.290     brouard   111:   Revision 1.289  2018/12/13 09:16:26  brouard
                    112:   Summary: Bug for young ages (<-30) will be in r17
                    113: 
1.289     brouard   114:   Revision 1.288  2018/05/02 20:58:27  brouard
                    115:   Summary: Some bugs fixed
                    116: 
1.288     brouard   117:   Revision 1.287  2018/05/01 17:57:25  brouard
                    118:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    119: 
1.287     brouard   120:   Revision 1.286  2018/04/27 14:27:04  brouard
                    121:   Summary: some minor bugs
                    122: 
1.286     brouard   123:   Revision 1.285  2018/04/21 21:02:16  brouard
                    124:   Summary: Some bugs fixed, valgrind tested
                    125: 
1.285     brouard   126:   Revision 1.284  2018/04/20 05:22:13  brouard
                    127:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    128: 
1.284     brouard   129:   Revision 1.283  2018/04/19 14:49:16  brouard
                    130:   Summary: Some minor bugs fixed
                    131: 
1.283     brouard   132:   Revision 1.282  2018/02/27 22:50:02  brouard
                    133:   *** empty log message ***
                    134: 
1.282     brouard   135:   Revision 1.281  2018/02/27 19:25:23  brouard
                    136:   Summary: Adding second argument for quitting
                    137: 
1.281     brouard   138:   Revision 1.280  2018/02/21 07:58:13  brouard
                    139:   Summary: 0.99r15
                    140: 
                    141:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    142: 
1.280     brouard   143:   Revision 1.279  2017/07/20 13:35:01  brouard
                    144:   Summary: temporary working
                    145: 
1.279     brouard   146:   Revision 1.278  2017/07/19 14:09:02  brouard
                    147:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    148: 
1.278     brouard   149:   Revision 1.277  2017/07/17 08:53:49  brouard
                    150:   Summary: BOM files can be read now
                    151: 
1.277     brouard   152:   Revision 1.276  2017/06/30 15:48:31  brouard
                    153:   Summary: Graphs improvements
                    154: 
1.276     brouard   155:   Revision 1.275  2017/06/30 13:39:33  brouard
                    156:   Summary: Saito's color
                    157: 
1.275     brouard   158:   Revision 1.274  2017/06/29 09:47:08  brouard
                    159:   Summary: Version 0.99r14
                    160: 
1.274     brouard   161:   Revision 1.273  2017/06/27 11:06:02  brouard
                    162:   Summary: More documentation on projections
                    163: 
1.273     brouard   164:   Revision 1.272  2017/06/27 10:22:40  brouard
                    165:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    166: 
1.272     brouard   167:   Revision 1.271  2017/06/27 10:17:50  brouard
                    168:   Summary: Some bug with rint
                    169: 
1.271     brouard   170:   Revision 1.270  2017/05/24 05:45:29  brouard
                    171:   *** empty log message ***
                    172: 
1.270     brouard   173:   Revision 1.269  2017/05/23 08:39:25  brouard
                    174:   Summary: Code into subroutine, cleanings
                    175: 
1.269     brouard   176:   Revision 1.268  2017/05/18 20:09:32  brouard
                    177:   Summary: backprojection and confidence intervals of backprevalence
                    178: 
1.268     brouard   179:   Revision 1.267  2017/05/13 10:25:05  brouard
                    180:   Summary: temporary save for backprojection
                    181: 
1.267     brouard   182:   Revision 1.266  2017/05/13 07:26:12  brouard
                    183:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    184: 
1.266     brouard   185:   Revision 1.265  2017/04/26 16:22:11  brouard
                    186:   Summary: imach 0.99r13 Some bugs fixed
                    187: 
1.265     brouard   188:   Revision 1.264  2017/04/26 06:01:29  brouard
                    189:   Summary: Labels in graphs
                    190: 
1.264     brouard   191:   Revision 1.263  2017/04/24 15:23:15  brouard
                    192:   Summary: to save
                    193: 
1.263     brouard   194:   Revision 1.262  2017/04/18 16:48:12  brouard
                    195:   *** empty log message ***
                    196: 
1.262     brouard   197:   Revision 1.261  2017/04/05 10:14:09  brouard
                    198:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    199: 
1.261     brouard   200:   Revision 1.260  2017/04/04 17:46:59  brouard
                    201:   Summary: Gnuplot indexations fixed (humm)
                    202: 
1.260     brouard   203:   Revision 1.259  2017/04/04 13:01:16  brouard
                    204:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    205: 
1.259     brouard   206:   Revision 1.258  2017/04/03 10:17:47  brouard
                    207:   Summary: Version 0.99r12
                    208: 
                    209:   Some cleanings, conformed with updated documentation.
                    210: 
1.258     brouard   211:   Revision 1.257  2017/03/29 16:53:30  brouard
                    212:   Summary: Temp
                    213: 
1.257     brouard   214:   Revision 1.256  2017/03/27 05:50:23  brouard
                    215:   Summary: Temporary
                    216: 
1.256     brouard   217:   Revision 1.255  2017/03/08 16:02:28  brouard
                    218:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    219: 
1.255     brouard   220:   Revision 1.254  2017/03/08 07:13:00  brouard
                    221:   Summary: Fixing data parameter line
                    222: 
1.254     brouard   223:   Revision 1.253  2016/12/15 11:59:41  brouard
                    224:   Summary: 0.99 in progress
                    225: 
1.253     brouard   226:   Revision 1.252  2016/09/15 21:15:37  brouard
                    227:   *** empty log message ***
                    228: 
1.252     brouard   229:   Revision 1.251  2016/09/15 15:01:13  brouard
                    230:   Summary: not working
                    231: 
1.251     brouard   232:   Revision 1.250  2016/09/08 16:07:27  brouard
                    233:   Summary: continue
                    234: 
1.250     brouard   235:   Revision 1.249  2016/09/07 17:14:18  brouard
                    236:   Summary: Starting values from frequencies
                    237: 
1.249     brouard   238:   Revision 1.248  2016/09/07 14:10:18  brouard
                    239:   *** empty log message ***
                    240: 
1.248     brouard   241:   Revision 1.247  2016/09/02 11:11:21  brouard
                    242:   *** empty log message ***
                    243: 
1.247     brouard   244:   Revision 1.246  2016/09/02 08:49:22  brouard
                    245:   *** empty log message ***
                    246: 
1.246     brouard   247:   Revision 1.245  2016/09/02 07:25:01  brouard
                    248:   *** empty log message ***
                    249: 
1.245     brouard   250:   Revision 1.244  2016/09/02 07:17:34  brouard
                    251:   *** empty log message ***
                    252: 
1.244     brouard   253:   Revision 1.243  2016/09/02 06:45:35  brouard
                    254:   *** empty log message ***
                    255: 
1.243     brouard   256:   Revision 1.242  2016/08/30 15:01:20  brouard
                    257:   Summary: Fixing a lots
                    258: 
1.242     brouard   259:   Revision 1.241  2016/08/29 17:17:25  brouard
                    260:   Summary: gnuplot problem in Back projection to fix
                    261: 
1.241     brouard   262:   Revision 1.240  2016/08/29 07:53:18  brouard
                    263:   Summary: Better
                    264: 
1.240     brouard   265:   Revision 1.239  2016/08/26 15:51:03  brouard
                    266:   Summary: Improvement in Powell output in order to copy and paste
                    267: 
                    268:   Author:
                    269: 
1.239     brouard   270:   Revision 1.238  2016/08/26 14:23:35  brouard
                    271:   Summary: Starting tests of 0.99
                    272: 
1.238     brouard   273:   Revision 1.237  2016/08/26 09:20:19  brouard
                    274:   Summary: to valgrind
                    275: 
1.237     brouard   276:   Revision 1.236  2016/08/25 10:50:18  brouard
                    277:   *** empty log message ***
                    278: 
1.236     brouard   279:   Revision 1.235  2016/08/25 06:59:23  brouard
                    280:   *** empty log message ***
                    281: 
1.235     brouard   282:   Revision 1.234  2016/08/23 16:51:20  brouard
                    283:   *** empty log message ***
                    284: 
1.234     brouard   285:   Revision 1.233  2016/08/23 07:40:50  brouard
                    286:   Summary: not working
                    287: 
1.233     brouard   288:   Revision 1.232  2016/08/22 14:20:21  brouard
                    289:   Summary: not working
                    290: 
1.232     brouard   291:   Revision 1.231  2016/08/22 07:17:15  brouard
                    292:   Summary: not working
                    293: 
1.231     brouard   294:   Revision 1.230  2016/08/22 06:55:53  brouard
                    295:   Summary: Not working
                    296: 
1.230     brouard   297:   Revision 1.229  2016/07/23 09:45:53  brouard
                    298:   Summary: Completing for func too
                    299: 
1.229     brouard   300:   Revision 1.228  2016/07/22 17:45:30  brouard
                    301:   Summary: Fixing some arrays, still debugging
                    302: 
1.227     brouard   303:   Revision 1.226  2016/07/12 18:42:34  brouard
                    304:   Summary: temp
                    305: 
1.226     brouard   306:   Revision 1.225  2016/07/12 08:40:03  brouard
                    307:   Summary: saving but not running
                    308: 
1.225     brouard   309:   Revision 1.224  2016/07/01 13:16:01  brouard
                    310:   Summary: Fixes
                    311: 
1.224     brouard   312:   Revision 1.223  2016/02/19 09:23:35  brouard
                    313:   Summary: temporary
                    314: 
1.223     brouard   315:   Revision 1.222  2016/02/17 08:14:50  brouard
                    316:   Summary: Probably last 0.98 stable version 0.98r6
                    317: 
1.222     brouard   318:   Revision 1.221  2016/02/15 23:35:36  brouard
                    319:   Summary: minor bug
                    320: 
1.220     brouard   321:   Revision 1.219  2016/02/15 00:48:12  brouard
                    322:   *** empty log message ***
                    323: 
1.219     brouard   324:   Revision 1.218  2016/02/12 11:29:23  brouard
                    325:   Summary: 0.99 Back projections
                    326: 
1.218     brouard   327:   Revision 1.217  2015/12/23 17:18:31  brouard
                    328:   Summary: Experimental backcast
                    329: 
1.217     brouard   330:   Revision 1.216  2015/12/18 17:32:11  brouard
                    331:   Summary: 0.98r4 Warning and status=-2
                    332: 
                    333:   Version 0.98r4 is now:
                    334:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    335:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    336:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    337: 
1.216     brouard   338:   Revision 1.215  2015/12/16 08:52:24  brouard
                    339:   Summary: 0.98r4 working
                    340: 
1.215     brouard   341:   Revision 1.214  2015/12/16 06:57:54  brouard
                    342:   Summary: temporary not working
                    343: 
1.214     brouard   344:   Revision 1.213  2015/12/11 18:22:17  brouard
                    345:   Summary: 0.98r4
                    346: 
1.213     brouard   347:   Revision 1.212  2015/11/21 12:47:24  brouard
                    348:   Summary: minor typo
                    349: 
1.212     brouard   350:   Revision 1.211  2015/11/21 12:41:11  brouard
                    351:   Summary: 0.98r3 with some graph of projected cross-sectional
                    352: 
                    353:   Author: Nicolas Brouard
                    354: 
1.211     brouard   355:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   356:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   357:   Summary: Adding ftolpl parameter
                    358:   Author: N Brouard
                    359: 
                    360:   We had difficulties to get smoothed confidence intervals. It was due
                    361:   to the period prevalence which wasn't computed accurately. The inner
                    362:   parameter ftolpl is now an outer parameter of the .imach parameter
                    363:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    364:   computation are long.
                    365: 
1.209     brouard   366:   Revision 1.208  2015/11/17 14:31:57  brouard
                    367:   Summary: temporary
                    368: 
1.208     brouard   369:   Revision 1.207  2015/10/27 17:36:57  brouard
                    370:   *** empty log message ***
                    371: 
1.207     brouard   372:   Revision 1.206  2015/10/24 07:14:11  brouard
                    373:   *** empty log message ***
                    374: 
1.206     brouard   375:   Revision 1.205  2015/10/23 15:50:53  brouard
                    376:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    377: 
1.205     brouard   378:   Revision 1.204  2015/10/01 16:20:26  brouard
                    379:   Summary: Some new graphs of contribution to likelihood
                    380: 
1.204     brouard   381:   Revision 1.203  2015/09/30 17:45:14  brouard
                    382:   Summary: looking at better estimation of the hessian
                    383: 
                    384:   Also a better criteria for convergence to the period prevalence And
                    385:   therefore adding the number of years needed to converge. (The
                    386:   prevalence in any alive state shold sum to one
                    387: 
1.203     brouard   388:   Revision 1.202  2015/09/22 19:45:16  brouard
                    389:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    390: 
1.202     brouard   391:   Revision 1.201  2015/09/15 17:34:58  brouard
                    392:   Summary: 0.98r0
                    393: 
                    394:   - Some new graphs like suvival functions
                    395:   - Some bugs fixed like model=1+age+V2.
                    396: 
1.201     brouard   397:   Revision 1.200  2015/09/09 16:53:55  brouard
                    398:   Summary: Big bug thanks to Flavia
                    399: 
                    400:   Even model=1+age+V2. did not work anymore
                    401: 
1.200     brouard   402:   Revision 1.199  2015/09/07 14:09:23  brouard
                    403:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    404: 
1.199     brouard   405:   Revision 1.198  2015/09/03 07:14:39  brouard
                    406:   Summary: 0.98q5 Flavia
                    407: 
1.198     brouard   408:   Revision 1.197  2015/09/01 18:24:39  brouard
                    409:   *** empty log message ***
                    410: 
1.197     brouard   411:   Revision 1.196  2015/08/18 23:17:52  brouard
                    412:   Summary: 0.98q5
                    413: 
1.196     brouard   414:   Revision 1.195  2015/08/18 16:28:39  brouard
                    415:   Summary: Adding a hack for testing purpose
                    416: 
                    417:   After reading the title, ftol and model lines, if the comment line has
                    418:   a q, starting with #q, the answer at the end of the run is quit. It
                    419:   permits to run test files in batch with ctest. The former workaround was
                    420:   $ echo q | imach foo.imach
                    421: 
1.195     brouard   422:   Revision 1.194  2015/08/18 13:32:00  brouard
                    423:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    424: 
1.194     brouard   425:   Revision 1.193  2015/08/04 07:17:42  brouard
                    426:   Summary: 0.98q4
                    427: 
1.193     brouard   428:   Revision 1.192  2015/07/16 16:49:02  brouard
                    429:   Summary: Fixing some outputs
                    430: 
1.192     brouard   431:   Revision 1.191  2015/07/14 10:00:33  brouard
                    432:   Summary: Some fixes
                    433: 
1.191     brouard   434:   Revision 1.190  2015/05/05 08:51:13  brouard
                    435:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    436: 
                    437:   Fix 1+age+.
                    438: 
1.190     brouard   439:   Revision 1.189  2015/04/30 14:45:16  brouard
                    440:   Summary: 0.98q2
                    441: 
1.189     brouard   442:   Revision 1.188  2015/04/30 08:27:53  brouard
                    443:   *** empty log message ***
                    444: 
1.188     brouard   445:   Revision 1.187  2015/04/29 09:11:15  brouard
                    446:   *** empty log message ***
                    447: 
1.187     brouard   448:   Revision 1.186  2015/04/23 12:01:52  brouard
                    449:   Summary: V1*age is working now, version 0.98q1
                    450: 
                    451:   Some codes had been disabled in order to simplify and Vn*age was
                    452:   working in the optimization phase, ie, giving correct MLE parameters,
                    453:   but, as usual, outputs were not correct and program core dumped.
                    454: 
1.186     brouard   455:   Revision 1.185  2015/03/11 13:26:42  brouard
                    456:   Summary: Inclusion of compile and links command line for Intel Compiler
                    457: 
1.185     brouard   458:   Revision 1.184  2015/03/11 11:52:39  brouard
                    459:   Summary: Back from Windows 8. Intel Compiler
                    460: 
1.184     brouard   461:   Revision 1.183  2015/03/10 20:34:32  brouard
                    462:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    463: 
                    464:   We use directest instead of original Powell test; probably no
                    465:   incidence on the results, but better justifications;
                    466:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    467:   wrong results.
                    468: 
1.183     brouard   469:   Revision 1.182  2015/02/12 08:19:57  brouard
                    470:   Summary: Trying to keep directest which seems simpler and more general
                    471:   Author: Nicolas Brouard
                    472: 
1.182     brouard   473:   Revision 1.181  2015/02/11 23:22:24  brouard
                    474:   Summary: Comments on Powell added
                    475: 
                    476:   Author:
                    477: 
1.181     brouard   478:   Revision 1.180  2015/02/11 17:33:45  brouard
                    479:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    480: 
1.180     brouard   481:   Revision 1.179  2015/01/04 09:57:06  brouard
                    482:   Summary: back to OS/X
                    483: 
1.179     brouard   484:   Revision 1.178  2015/01/04 09:35:48  brouard
                    485:   *** empty log message ***
                    486: 
1.178     brouard   487:   Revision 1.177  2015/01/03 18:40:56  brouard
                    488:   Summary: Still testing ilc32 on OSX
                    489: 
1.177     brouard   490:   Revision 1.176  2015/01/03 16:45:04  brouard
                    491:   *** empty log message ***
                    492: 
1.176     brouard   493:   Revision 1.175  2015/01/03 16:33:42  brouard
                    494:   *** empty log message ***
                    495: 
1.175     brouard   496:   Revision 1.174  2015/01/03 16:15:49  brouard
                    497:   Summary: Still in cross-compilation
                    498: 
1.174     brouard   499:   Revision 1.173  2015/01/03 12:06:26  brouard
                    500:   Summary: trying to detect cross-compilation
                    501: 
1.173     brouard   502:   Revision 1.172  2014/12/27 12:07:47  brouard
                    503:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    504: 
1.172     brouard   505:   Revision 1.171  2014/12/23 13:26:59  brouard
                    506:   Summary: Back from Visual C
                    507: 
                    508:   Still problem with utsname.h on Windows
                    509: 
1.171     brouard   510:   Revision 1.170  2014/12/23 11:17:12  brouard
                    511:   Summary: Cleaning some \%% back to %%
                    512: 
                    513:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    514: 
1.170     brouard   515:   Revision 1.169  2014/12/22 23:08:31  brouard
                    516:   Summary: 0.98p
                    517: 
                    518:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    519: 
1.169     brouard   520:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   521:   Summary: update
1.169     brouard   522: 
1.168     brouard   523:   Revision 1.167  2014/12/22 13:50:56  brouard
                    524:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    525: 
                    526:   Testing on Linux 64
                    527: 
1.167     brouard   528:   Revision 1.166  2014/12/22 11:40:47  brouard
                    529:   *** empty log message ***
                    530: 
1.166     brouard   531:   Revision 1.165  2014/12/16 11:20:36  brouard
                    532:   Summary: After compiling on Visual C
                    533: 
                    534:   * imach.c (Module): Merging 1.61 to 1.162
                    535: 
1.165     brouard   536:   Revision 1.164  2014/12/16 10:52:11  brouard
                    537:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    538: 
                    539:   * imach.c (Module): Merging 1.61 to 1.162
                    540: 
1.164     brouard   541:   Revision 1.163  2014/12/16 10:30:11  brouard
                    542:   * imach.c (Module): Merging 1.61 to 1.162
                    543: 
1.163     brouard   544:   Revision 1.162  2014/09/25 11:43:39  brouard
                    545:   Summary: temporary backup 0.99!
                    546: 
1.162     brouard   547:   Revision 1.1  2014/09/16 11:06:58  brouard
                    548:   Summary: With some code (wrong) for nlopt
                    549: 
                    550:   Author:
                    551: 
                    552:   Revision 1.161  2014/09/15 20:41:41  brouard
                    553:   Summary: Problem with macro SQR on Intel compiler
                    554: 
1.161     brouard   555:   Revision 1.160  2014/09/02 09:24:05  brouard
                    556:   *** empty log message ***
                    557: 
1.160     brouard   558:   Revision 1.159  2014/09/01 10:34:10  brouard
                    559:   Summary: WIN32
                    560:   Author: Brouard
                    561: 
1.159     brouard   562:   Revision 1.158  2014/08/27 17:11:51  brouard
                    563:   *** empty log message ***
                    564: 
1.158     brouard   565:   Revision 1.157  2014/08/27 16:26:55  brouard
                    566:   Summary: Preparing windows Visual studio version
                    567:   Author: Brouard
                    568: 
                    569:   In order to compile on Visual studio, time.h is now correct and time_t
                    570:   and tm struct should be used. difftime should be used but sometimes I
                    571:   just make the differences in raw time format (time(&now).
                    572:   Trying to suppress #ifdef LINUX
                    573:   Add xdg-open for __linux in order to open default browser.
                    574: 
1.157     brouard   575:   Revision 1.156  2014/08/25 20:10:10  brouard
                    576:   *** empty log message ***
                    577: 
1.156     brouard   578:   Revision 1.155  2014/08/25 18:32:34  brouard
                    579:   Summary: New compile, minor changes
                    580:   Author: Brouard
                    581: 
1.155     brouard   582:   Revision 1.154  2014/06/20 17:32:08  brouard
                    583:   Summary: Outputs now all graphs of convergence to period prevalence
                    584: 
1.154     brouard   585:   Revision 1.153  2014/06/20 16:45:46  brouard
                    586:   Summary: If 3 live state, convergence to period prevalence on same graph
                    587:   Author: Brouard
                    588: 
1.153     brouard   589:   Revision 1.152  2014/06/18 17:54:09  brouard
                    590:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    591: 
1.152     brouard   592:   Revision 1.151  2014/06/18 16:43:30  brouard
                    593:   *** empty log message ***
                    594: 
1.151     brouard   595:   Revision 1.150  2014/06/18 16:42:35  brouard
                    596:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    597:   Author: brouard
                    598: 
1.150     brouard   599:   Revision 1.149  2014/06/18 15:51:14  brouard
                    600:   Summary: Some fixes in parameter files errors
                    601:   Author: Nicolas Brouard
                    602: 
1.149     brouard   603:   Revision 1.148  2014/06/17 17:38:48  brouard
                    604:   Summary: Nothing new
                    605:   Author: Brouard
                    606: 
                    607:   Just a new packaging for OS/X version 0.98nS
                    608: 
1.148     brouard   609:   Revision 1.147  2014/06/16 10:33:11  brouard
                    610:   *** empty log message ***
                    611: 
1.147     brouard   612:   Revision 1.146  2014/06/16 10:20:28  brouard
                    613:   Summary: Merge
                    614:   Author: Brouard
                    615: 
                    616:   Merge, before building revised version.
                    617: 
1.146     brouard   618:   Revision 1.145  2014/06/10 21:23:15  brouard
                    619:   Summary: Debugging with valgrind
                    620:   Author: Nicolas Brouard
                    621: 
                    622:   Lot of changes in order to output the results with some covariates
                    623:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    624:   improve the code.
                    625:   No more memory valgrind error but a lot has to be done in order to
                    626:   continue the work of splitting the code into subroutines.
                    627:   Also, decodemodel has been improved. Tricode is still not
                    628:   optimal. nbcode should be improved. Documentation has been added in
                    629:   the source code.
                    630: 
1.144     brouard   631:   Revision 1.143  2014/01/26 09:45:38  brouard
                    632:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    633: 
                    634:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    635:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    636: 
1.143     brouard   637:   Revision 1.142  2014/01/26 03:57:36  brouard
                    638:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    639: 
                    640:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    641: 
1.142     brouard   642:   Revision 1.141  2014/01/26 02:42:01  brouard
                    643:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    644: 
1.141     brouard   645:   Revision 1.140  2011/09/02 10:37:54  brouard
                    646:   Summary: times.h is ok with mingw32 now.
                    647: 
1.140     brouard   648:   Revision 1.139  2010/06/14 07:50:17  brouard
                    649:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    650:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    651: 
1.139     brouard   652:   Revision 1.138  2010/04/30 18:19:40  brouard
                    653:   *** empty log message ***
                    654: 
1.138     brouard   655:   Revision 1.137  2010/04/29 18:11:38  brouard
                    656:   (Module): Checking covariates for more complex models
                    657:   than V1+V2. A lot of change to be done. Unstable.
                    658: 
1.137     brouard   659:   Revision 1.136  2010/04/26 20:30:53  brouard
                    660:   (Module): merging some libgsl code. Fixing computation
                    661:   of likelione (using inter/intrapolation if mle = 0) in order to
                    662:   get same likelihood as if mle=1.
                    663:   Some cleaning of code and comments added.
                    664: 
1.136     brouard   665:   Revision 1.135  2009/10/29 15:33:14  brouard
                    666:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    667: 
1.135     brouard   668:   Revision 1.134  2009/10/29 13:18:53  brouard
                    669:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    670: 
1.134     brouard   671:   Revision 1.133  2009/07/06 10:21:25  brouard
                    672:   just nforces
                    673: 
1.133     brouard   674:   Revision 1.132  2009/07/06 08:22:05  brouard
                    675:   Many tings
                    676: 
1.132     brouard   677:   Revision 1.131  2009/06/20 16:22:47  brouard
                    678:   Some dimensions resccaled
                    679: 
1.131     brouard   680:   Revision 1.130  2009/05/26 06:44:34  brouard
                    681:   (Module): Max Covariate is now set to 20 instead of 8. A
                    682:   lot of cleaning with variables initialized to 0. Trying to make
                    683:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    684: 
1.130     brouard   685:   Revision 1.129  2007/08/31 13:49:27  lievre
                    686:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    687: 
1.129     lievre    688:   Revision 1.128  2006/06/30 13:02:05  brouard
                    689:   (Module): Clarifications on computing e.j
                    690: 
1.128     brouard   691:   Revision 1.127  2006/04/28 18:11:50  brouard
                    692:   (Module): Yes the sum of survivors was wrong since
                    693:   imach-114 because nhstepm was no more computed in the age
                    694:   loop. Now we define nhstepma in the age loop.
                    695:   (Module): In order to speed up (in case of numerous covariates) we
                    696:   compute health expectancies (without variances) in a first step
                    697:   and then all the health expectancies with variances or standard
                    698:   deviation (needs data from the Hessian matrices) which slows the
                    699:   computation.
                    700:   In the future we should be able to stop the program is only health
                    701:   expectancies and graph are needed without standard deviations.
                    702: 
1.127     brouard   703:   Revision 1.126  2006/04/28 17:23:28  brouard
                    704:   (Module): Yes the sum of survivors was wrong since
                    705:   imach-114 because nhstepm was no more computed in the age
                    706:   loop. Now we define nhstepma in the age loop.
                    707:   Version 0.98h
                    708: 
1.126     brouard   709:   Revision 1.125  2006/04/04 15:20:31  lievre
                    710:   Errors in calculation of health expectancies. Age was not initialized.
                    711:   Forecasting file added.
                    712: 
                    713:   Revision 1.124  2006/03/22 17:13:53  lievre
                    714:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    715:   The log-likelihood is printed in the log file
                    716: 
                    717:   Revision 1.123  2006/03/20 10:52:43  brouard
                    718:   * imach.c (Module): <title> changed, corresponds to .htm file
                    719:   name. <head> headers where missing.
                    720: 
                    721:   * imach.c (Module): Weights can have a decimal point as for
                    722:   English (a comma might work with a correct LC_NUMERIC environment,
                    723:   otherwise the weight is truncated).
                    724:   Modification of warning when the covariates values are not 0 or
                    725:   1.
                    726:   Version 0.98g
                    727: 
                    728:   Revision 1.122  2006/03/20 09:45:41  brouard
                    729:   (Module): Weights can have a decimal point as for
                    730:   English (a comma might work with a correct LC_NUMERIC environment,
                    731:   otherwise the weight is truncated).
                    732:   Modification of warning when the covariates values are not 0 or
                    733:   1.
                    734:   Version 0.98g
                    735: 
                    736:   Revision 1.121  2006/03/16 17:45:01  lievre
                    737:   * imach.c (Module): Comments concerning covariates added
                    738: 
                    739:   * imach.c (Module): refinements in the computation of lli if
                    740:   status=-2 in order to have more reliable computation if stepm is
                    741:   not 1 month. Version 0.98f
                    742: 
                    743:   Revision 1.120  2006/03/16 15:10:38  lievre
                    744:   (Module): refinements in the computation of lli if
                    745:   status=-2 in order to have more reliable computation if stepm is
                    746:   not 1 month. Version 0.98f
                    747: 
                    748:   Revision 1.119  2006/03/15 17:42:26  brouard
                    749:   (Module): Bug if status = -2, the loglikelihood was
                    750:   computed as likelihood omitting the logarithm. Version O.98e
                    751: 
                    752:   Revision 1.118  2006/03/14 18:20:07  brouard
                    753:   (Module): varevsij Comments added explaining the second
                    754:   table of variances if popbased=1 .
                    755:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    756:   (Module): Function pstamp added
                    757:   (Module): Version 0.98d
                    758: 
                    759:   Revision 1.117  2006/03/14 17:16:22  brouard
                    760:   (Module): varevsij Comments added explaining the second
                    761:   table of variances if popbased=1 .
                    762:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    763:   (Module): Function pstamp added
                    764:   (Module): Version 0.98d
                    765: 
                    766:   Revision 1.116  2006/03/06 10:29:27  brouard
                    767:   (Module): Variance-covariance wrong links and
                    768:   varian-covariance of ej. is needed (Saito).
                    769: 
                    770:   Revision 1.115  2006/02/27 12:17:45  brouard
                    771:   (Module): One freematrix added in mlikeli! 0.98c
                    772: 
                    773:   Revision 1.114  2006/02/26 12:57:58  brouard
                    774:   (Module): Some improvements in processing parameter
                    775:   filename with strsep.
                    776: 
                    777:   Revision 1.113  2006/02/24 14:20:24  brouard
                    778:   (Module): Memory leaks checks with valgrind and:
                    779:   datafile was not closed, some imatrix were not freed and on matrix
                    780:   allocation too.
                    781: 
                    782:   Revision 1.112  2006/01/30 09:55:26  brouard
                    783:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    784: 
                    785:   Revision 1.111  2006/01/25 20:38:18  brouard
                    786:   (Module): Lots of cleaning and bugs added (Gompertz)
                    787:   (Module): Comments can be added in data file. Missing date values
                    788:   can be a simple dot '.'.
                    789: 
                    790:   Revision 1.110  2006/01/25 00:51:50  brouard
                    791:   (Module): Lots of cleaning and bugs added (Gompertz)
                    792: 
                    793:   Revision 1.109  2006/01/24 19:37:15  brouard
                    794:   (Module): Comments (lines starting with a #) are allowed in data.
                    795: 
                    796:   Revision 1.108  2006/01/19 18:05:42  lievre
                    797:   Gnuplot problem appeared...
                    798:   To be fixed
                    799: 
                    800:   Revision 1.107  2006/01/19 16:20:37  brouard
                    801:   Test existence of gnuplot in imach path
                    802: 
                    803:   Revision 1.106  2006/01/19 13:24:36  brouard
                    804:   Some cleaning and links added in html output
                    805: 
                    806:   Revision 1.105  2006/01/05 20:23:19  lievre
                    807:   *** empty log message ***
                    808: 
                    809:   Revision 1.104  2005/09/30 16:11:43  lievre
                    810:   (Module): sump fixed, loop imx fixed, and simplifications.
                    811:   (Module): If the status is missing at the last wave but we know
                    812:   that the person is alive, then we can code his/her status as -2
                    813:   (instead of missing=-1 in earlier versions) and his/her
                    814:   contributions to the likelihood is 1 - Prob of dying from last
                    815:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    816:   the healthy state at last known wave). Version is 0.98
                    817: 
                    818:   Revision 1.103  2005/09/30 15:54:49  lievre
                    819:   (Module): sump fixed, loop imx fixed, and simplifications.
                    820: 
                    821:   Revision 1.102  2004/09/15 17:31:30  brouard
                    822:   Add the possibility to read data file including tab characters.
                    823: 
                    824:   Revision 1.101  2004/09/15 10:38:38  brouard
                    825:   Fix on curr_time
                    826: 
                    827:   Revision 1.100  2004/07/12 18:29:06  brouard
                    828:   Add version for Mac OS X. Just define UNIX in Makefile
                    829: 
                    830:   Revision 1.99  2004/06/05 08:57:40  brouard
                    831:   *** empty log message ***
                    832: 
                    833:   Revision 1.98  2004/05/16 15:05:56  brouard
                    834:   New version 0.97 . First attempt to estimate force of mortality
                    835:   directly from the data i.e. without the need of knowing the health
                    836:   state at each age, but using a Gompertz model: log u =a + b*age .
                    837:   This is the basic analysis of mortality and should be done before any
                    838:   other analysis, in order to test if the mortality estimated from the
                    839:   cross-longitudinal survey is different from the mortality estimated
                    840:   from other sources like vital statistic data.
                    841: 
                    842:   The same imach parameter file can be used but the option for mle should be -3.
                    843: 
1.133     brouard   844:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   845:   former routines in order to include the new code within the former code.
                    846: 
                    847:   The output is very simple: only an estimate of the intercept and of
                    848:   the slope with 95% confident intervals.
                    849: 
                    850:   Current limitations:
                    851:   A) Even if you enter covariates, i.e. with the
                    852:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    853:   B) There is no computation of Life Expectancy nor Life Table.
                    854: 
                    855:   Revision 1.97  2004/02/20 13:25:42  lievre
                    856:   Version 0.96d. Population forecasting command line is (temporarily)
                    857:   suppressed.
                    858: 
                    859:   Revision 1.96  2003/07/15 15:38:55  brouard
                    860:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    861:   rewritten within the same printf. Workaround: many printfs.
                    862: 
                    863:   Revision 1.95  2003/07/08 07:54:34  brouard
                    864:   * imach.c (Repository):
                    865:   (Repository): Using imachwizard code to output a more meaningful covariance
                    866:   matrix (cov(a12,c31) instead of numbers.
                    867: 
                    868:   Revision 1.94  2003/06/27 13:00:02  brouard
                    869:   Just cleaning
                    870: 
                    871:   Revision 1.93  2003/06/25 16:33:55  brouard
                    872:   (Module): On windows (cygwin) function asctime_r doesn't
                    873:   exist so I changed back to asctime which exists.
                    874:   (Module): Version 0.96b
                    875: 
                    876:   Revision 1.92  2003/06/25 16:30:45  brouard
                    877:   (Module): On windows (cygwin) function asctime_r doesn't
                    878:   exist so I changed back to asctime which exists.
                    879: 
                    880:   Revision 1.91  2003/06/25 15:30:29  brouard
                    881:   * imach.c (Repository): Duplicated warning errors corrected.
                    882:   (Repository): Elapsed time after each iteration is now output. It
                    883:   helps to forecast when convergence will be reached. Elapsed time
                    884:   is stamped in powell.  We created a new html file for the graphs
                    885:   concerning matrix of covariance. It has extension -cov.htm.
                    886: 
                    887:   Revision 1.90  2003/06/24 12:34:15  brouard
                    888:   (Module): Some bugs corrected for windows. Also, when
                    889:   mle=-1 a template is output in file "or"mypar.txt with the design
                    890:   of the covariance matrix to be input.
                    891: 
                    892:   Revision 1.89  2003/06/24 12:30:52  brouard
                    893:   (Module): Some bugs corrected for windows. Also, when
                    894:   mle=-1 a template is output in file "or"mypar.txt with the design
                    895:   of the covariance matrix to be input.
                    896: 
                    897:   Revision 1.88  2003/06/23 17:54:56  brouard
                    898:   * 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.
                    899: 
                    900:   Revision 1.87  2003/06/18 12:26:01  brouard
                    901:   Version 0.96
                    902: 
                    903:   Revision 1.86  2003/06/17 20:04:08  brouard
                    904:   (Module): Change position of html and gnuplot routines and added
                    905:   routine fileappend.
                    906: 
                    907:   Revision 1.85  2003/06/17 13:12:43  brouard
                    908:   * imach.c (Repository): Check when date of death was earlier that
                    909:   current date of interview. It may happen when the death was just
                    910:   prior to the death. In this case, dh was negative and likelihood
                    911:   was wrong (infinity). We still send an "Error" but patch by
                    912:   assuming that the date of death was just one stepm after the
                    913:   interview.
                    914:   (Repository): Because some people have very long ID (first column)
                    915:   we changed int to long in num[] and we added a new lvector for
                    916:   memory allocation. But we also truncated to 8 characters (left
                    917:   truncation)
                    918:   (Repository): No more line truncation errors.
                    919: 
                    920:   Revision 1.84  2003/06/13 21:44:43  brouard
                    921:   * imach.c (Repository): Replace "freqsummary" at a correct
                    922:   place. It differs from routine "prevalence" which may be called
                    923:   many times. Probs is memory consuming and must be used with
                    924:   parcimony.
                    925:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    926: 
                    927:   Revision 1.83  2003/06/10 13:39:11  lievre
                    928:   *** empty log message ***
                    929: 
                    930:   Revision 1.82  2003/06/05 15:57:20  brouard
                    931:   Add log in  imach.c and  fullversion number is now printed.
                    932: 
                    933: */
                    934: /*
                    935:    Interpolated Markov Chain
                    936: 
                    937:   Short summary of the programme:
                    938:   
1.227     brouard   939:   This program computes Healthy Life Expectancies or State-specific
                    940:   (if states aren't health statuses) Expectancies from
                    941:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    942: 
                    943:   -1- a first survey ("cross") where individuals from different ages
                    944:   are interviewed on their health status or degree of disability (in
                    945:   the case of a health survey which is our main interest)
                    946: 
                    947:   -2- at least a second wave of interviews ("longitudinal") which
                    948:   measure each change (if any) in individual health status.  Health
                    949:   expectancies are computed from the time spent in each health state
                    950:   according to a model. More health states you consider, more time is
                    951:   necessary to reach the Maximum Likelihood of the parameters involved
                    952:   in the model.  The simplest model is the multinomial logistic model
                    953:   where pij is the probability to be observed in state j at the second
                    954:   wave conditional to be observed in state i at the first
                    955:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    956:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    957:   have a more complex model than "constant and age", you should modify
                    958:   the program where the markup *Covariates have to be included here
                    959:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   960:   convergence.
                    961: 
                    962:   The advantage of this computer programme, compared to a simple
                    963:   multinomial logistic model, is clear when the delay between waves is not
                    964:   identical for each individual. Also, if a individual missed an
                    965:   intermediate interview, the information is lost, but taken into
                    966:   account using an interpolation or extrapolation.  
                    967: 
                    968:   hPijx is the probability to be observed in state i at age x+h
                    969:   conditional to the observed state i at age x. The delay 'h' can be
                    970:   split into an exact number (nh*stepm) of unobserved intermediate
                    971:   states. This elementary transition (by month, quarter,
                    972:   semester or year) is modelled as a multinomial logistic.  The hPx
                    973:   matrix is simply the matrix product of nh*stepm elementary matrices
                    974:   and the contribution of each individual to the likelihood is simply
                    975:   hPijx.
                    976: 
                    977:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   978:   of the life expectancies. It also computes the period (stable) prevalence.
                    979: 
                    980: Back prevalence and projections:
1.227     brouard   981: 
                    982:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    983:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    984:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    985:    mobilavproj)
                    986: 
                    987:     Computes the back prevalence limit for any combination of
                    988:     covariate values k at any age between ageminpar and agemaxpar and
                    989:     returns it in **bprlim. In the loops,
                    990: 
                    991:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    992:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    993: 
                    994:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   995:    Computes for any combination of covariates k and any age between bage and fage 
                    996:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    997:                        oldm=oldms;savm=savms;
1.227     brouard   998: 
1.267     brouard   999:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1000:      Computes the transition matrix starting at age 'age' over
                   1001:      'nhstepm*hstepm*stepm' months (i.e. until
                   1002:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1003:      nhstepm*hstepm matrices. 
                   1004: 
                   1005:      Returns p3mat[i][j][h] after calling
                   1006:      p3mat[i][j][h]=matprod2(newm,
                   1007:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1008:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1009:      oldm);
1.226     brouard  1010: 
                   1011: Important routines
                   1012: 
                   1013: - func (or funcone), computes logit (pij) distinguishing
                   1014:   o fixed variables (single or product dummies or quantitative);
                   1015:   o varying variables by:
                   1016:    (1) wave (single, product dummies, quantitative), 
                   1017:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1018:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1019:        % varying dummy (not done) or quantitative (not done);
                   1020: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1021:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1022: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                   1023:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                   1024:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1025: 
1.226     brouard  1026: 
                   1027:   
1.133     brouard  1028:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1029:            Institut national d'études démographiques, Paris.
1.126     brouard  1030:   This software have been partly granted by Euro-REVES, a concerted action
                   1031:   from the European Union.
                   1032:   It is copyrighted identically to a GNU software product, ie programme and
                   1033:   software can be distributed freely for non commercial use. Latest version
                   1034:   can be accessed at http://euroreves.ined.fr/imach .
                   1035: 
                   1036:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1037:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1038:   
                   1039:   **********************************************************************/
                   1040: /*
                   1041:   main
                   1042:   read parameterfile
                   1043:   read datafile
                   1044:   concatwav
                   1045:   freqsummary
                   1046:   if (mle >= 1)
                   1047:     mlikeli
                   1048:   print results files
                   1049:   if mle==1 
                   1050:      computes hessian
                   1051:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1052:       begin-prev-date,...
                   1053:   open gnuplot file
                   1054:   open html file
1.145     brouard  1055:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1056:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1057:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1058:     freexexit2 possible for memory heap.
                   1059: 
                   1060:   h Pij x                         | pij_nom  ficrestpij
                   1061:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1062:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1063:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1064: 
                   1065:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1066:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1067:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1068:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1069:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1070: 
1.126     brouard  1071:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1072:   health expectancies
                   1073:   Variance-covariance of DFLE
                   1074:   prevalence()
                   1075:    movingaverage()
                   1076:   varevsij() 
                   1077:   if popbased==1 varevsij(,popbased)
                   1078:   total life expectancies
                   1079:   Variance of period (stable) prevalence
                   1080:  end
                   1081: */
                   1082: 
1.187     brouard  1083: /* #define DEBUG */
                   1084: /* #define DEBUGBRENT */
1.203     brouard  1085: /* #define DEBUGLINMIN */
                   1086: /* #define DEBUGHESS */
                   1087: #define DEBUGHESSIJ
1.224     brouard  1088: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1089: #define POWELL /* Instead of NLOPT */
1.224     brouard  1090: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1091: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1092: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1093: 
                   1094: #include <math.h>
                   1095: #include <stdio.h>
                   1096: #include <stdlib.h>
                   1097: #include <string.h>
1.226     brouard  1098: #include <ctype.h>
1.159     brouard  1099: 
                   1100: #ifdef _WIN32
                   1101: #include <io.h>
1.172     brouard  1102: #include <windows.h>
                   1103: #include <tchar.h>
1.159     brouard  1104: #else
1.126     brouard  1105: #include <unistd.h>
1.159     brouard  1106: #endif
1.126     brouard  1107: 
                   1108: #include <limits.h>
                   1109: #include <sys/types.h>
1.171     brouard  1110: 
                   1111: #if defined(__GNUC__)
                   1112: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1113: #endif
                   1114: 
1.126     brouard  1115: #include <sys/stat.h>
                   1116: #include <errno.h>
1.159     brouard  1117: /* extern int errno; */
1.126     brouard  1118: 
1.157     brouard  1119: /* #ifdef LINUX */
                   1120: /* #include <time.h> */
                   1121: /* #include "timeval.h" */
                   1122: /* #else */
                   1123: /* #include <sys/time.h> */
                   1124: /* #endif */
                   1125: 
1.126     brouard  1126: #include <time.h>
                   1127: 
1.136     brouard  1128: #ifdef GSL
                   1129: #include <gsl/gsl_errno.h>
                   1130: #include <gsl/gsl_multimin.h>
                   1131: #endif
                   1132: 
1.167     brouard  1133: 
1.162     brouard  1134: #ifdef NLOPT
                   1135: #include <nlopt.h>
                   1136: typedef struct {
                   1137:   double (* function)(double [] );
                   1138: } myfunc_data ;
                   1139: #endif
                   1140: 
1.126     brouard  1141: /* #include <libintl.h> */
                   1142: /* #define _(String) gettext (String) */
                   1143: 
1.251     brouard  1144: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1145: 
                   1146: #define GNUPLOTPROGRAM "gnuplot"
                   1147: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1148: #define FILENAMELENGTH 132
                   1149: 
                   1150: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1151: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1152: 
1.144     brouard  1153: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1154: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1155: 
                   1156: #define NINTERVMAX 8
1.144     brouard  1157: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1158: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1159: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1160: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1161: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1162: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1163: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1164: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1165: /* #define AGESUP 130 */
1.288     brouard  1166: /* #define AGESUP 150 */
                   1167: #define AGESUP 200
1.268     brouard  1168: #define AGEINF 0
1.218     brouard  1169: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1170: #define AGEBASE 40
1.194     brouard  1171: #define AGEOVERFLOW 1.e20
1.164     brouard  1172: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1173: #ifdef _WIN32
                   1174: #define DIRSEPARATOR '\\'
                   1175: #define CHARSEPARATOR "\\"
                   1176: #define ODIRSEPARATOR '/'
                   1177: #else
1.126     brouard  1178: #define DIRSEPARATOR '/'
                   1179: #define CHARSEPARATOR "/"
                   1180: #define ODIRSEPARATOR '\\'
                   1181: #endif
                   1182: 
1.316   ! brouard  1183: /* $Id: imach.c,v 1.315 2022/05/11 15:06:32 brouard Exp $ */
1.126     brouard  1184: /* $State: Exp $ */
1.196     brouard  1185: #include "version.h"
                   1186: char version[]=__IMACH_VERSION__;
1.316   ! brouard  1187: 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";
        !          1188: char fullversion[]="$Revision: 1.315 $ $Date: 2022/05/11 15:06:32 $"; 
1.126     brouard  1189: char strstart[80];
                   1190: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1191: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1192: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1193: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1194: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1195: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1196: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1197: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1198: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1199: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1200: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1201: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1202: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1203: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1204: int nsd=0; /**< Total number of single dummy variables (output) */
                   1205: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1206: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1207: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1208: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1209: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1210: int cptcov=0; /* Working variable */
1.290     brouard  1211: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1212: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1213: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1214: int nlstate=2; /* Number of live states */
                   1215: int ndeath=1; /* Number of dead states */
1.130     brouard  1216: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1217: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1218: int popbased=0;
                   1219: 
                   1220: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1221: int maxwav=0; /* Maxim number of waves */
                   1222: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1223: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1224: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1225:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1226: int mle=1, weightopt=0;
1.126     brouard  1227: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1228: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1229: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1230:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1231: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1232: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1233: 
1.130     brouard  1234: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1235: double **matprod2(); /* test */
1.126     brouard  1236: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1237: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1238: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1239: 
1.136     brouard  1240: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1241: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1242: FILE *ficlog, *ficrespow;
1.130     brouard  1243: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1244: double fretone; /* Only one call to likelihood */
1.130     brouard  1245: long ipmx=0; /* Number of contributions */
1.126     brouard  1246: double sw; /* Sum of weights */
                   1247: char filerespow[FILENAMELENGTH];
                   1248: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1249: FILE *ficresilk;
                   1250: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1251: FILE *ficresprobmorprev;
                   1252: FILE *fichtm, *fichtmcov; /* Html File */
                   1253: FILE *ficreseij;
                   1254: char filerese[FILENAMELENGTH];
                   1255: FILE *ficresstdeij;
                   1256: char fileresstde[FILENAMELENGTH];
                   1257: FILE *ficrescveij;
                   1258: char filerescve[FILENAMELENGTH];
                   1259: FILE  *ficresvij;
                   1260: char fileresv[FILENAMELENGTH];
1.269     brouard  1261: 
1.126     brouard  1262: char title[MAXLINE];
1.234     brouard  1263: char model[MAXLINE]; /**< The model line */
1.217     brouard  1264: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1265: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1266: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1267: char command[FILENAMELENGTH];
                   1268: int  outcmd=0;
                   1269: 
1.217     brouard  1270: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1271: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1272: char filelog[FILENAMELENGTH]; /* Log file */
                   1273: char filerest[FILENAMELENGTH];
                   1274: char fileregp[FILENAMELENGTH];
                   1275: char popfile[FILENAMELENGTH];
                   1276: 
                   1277: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1278: 
1.157     brouard  1279: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1280: /* struct timezone tzp; */
                   1281: /* extern int gettimeofday(); */
                   1282: struct tm tml, *gmtime(), *localtime();
                   1283: 
                   1284: extern time_t time();
                   1285: 
                   1286: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1287: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1288: struct tm tm;
                   1289: 
1.126     brouard  1290: char strcurr[80], strfor[80];
                   1291: 
                   1292: char *endptr;
                   1293: long lval;
                   1294: double dval;
                   1295: 
                   1296: #define NR_END 1
                   1297: #define FREE_ARG char*
                   1298: #define FTOL 1.0e-10
                   1299: 
                   1300: #define NRANSI 
1.240     brouard  1301: #define ITMAX 200
                   1302: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1303: 
                   1304: #define TOL 2.0e-4 
                   1305: 
                   1306: #define CGOLD 0.3819660 
                   1307: #define ZEPS 1.0e-10 
                   1308: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1309: 
                   1310: #define GOLD 1.618034 
                   1311: #define GLIMIT 100.0 
                   1312: #define TINY 1.0e-20 
                   1313: 
                   1314: static double maxarg1,maxarg2;
                   1315: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1316: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1317:   
                   1318: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1319: #define rint(a) floor(a+0.5)
1.166     brouard  1320: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1321: #define mytinydouble 1.0e-16
1.166     brouard  1322: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1323: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1324: /* static double dsqrarg; */
                   1325: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1326: static double sqrarg;
                   1327: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1328: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1329: int agegomp= AGEGOMP;
                   1330: 
                   1331: int imx; 
                   1332: int stepm=1;
                   1333: /* Stepm, step in month: minimum step interpolation*/
                   1334: 
                   1335: int estepm;
                   1336: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1337: 
                   1338: int m,nb;
                   1339: long *num;
1.197     brouard  1340: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1341: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1342:                   covariate for which somebody answered excluding 
                   1343:                   undefined. Usually 2: 0 and 1. */
                   1344: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1345:                             covariate for which somebody answered including 
                   1346:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1347: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1348: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1349: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1350: double *ageexmed,*agecens;
                   1351: double dateintmean=0;
1.296     brouard  1352:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1353:   double anprojf, mprojf, jprojf;
1.126     brouard  1354: 
1.296     brouard  1355:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1356:   double anbackf, mbackf, jbackf;
                   1357:   double jintmean,mintmean,aintmean;  
1.126     brouard  1358: double *weight;
                   1359: int **s; /* Status */
1.141     brouard  1360: double *agedc;
1.145     brouard  1361: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1362:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1363:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1364: double **coqvar; /* Fixed quantitative covariate nqv */
                   1365: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1366: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1367: double  idx; 
                   1368: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1369: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1370: /*k          1  2   3   4     5    6    7     8    9 */
                   1371: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1372: /* Tndvar[k]    1   2   3               4          5 */
                   1373: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1374: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1375: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1376: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1377: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1378: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1379: /* Tprod[i]=k           4               7            */
                   1380: /* Tage[i]=k                  5               8      */
                   1381: /* */
                   1382: /* Type                    */
                   1383: /* V         1  2  3  4  5 */
                   1384: /*           F  F  V  V  V */
                   1385: /*           D  Q  D  D  Q */
                   1386: /*                         */
                   1387: int *TvarsD;
                   1388: int *TvarsDind;
                   1389: int *TvarsQ;
                   1390: int *TvarsQind;
                   1391: 
1.235     brouard  1392: #define MAXRESULTLINES 10
                   1393: int nresult=0;
1.258     brouard  1394: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1395: int TKresult[MAXRESULTLINES];
1.237     brouard  1396: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1397: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1398: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1399: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1400: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1401: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1402: 
1.234     brouard  1403: /* 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  1404: 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 */
                   1405: 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 */
                   1406: 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 */
                   1407: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1408: 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 */
                   1409: 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  1410: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1411: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1412: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1413: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1414: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1415: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1416: 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 */
                   1417: 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 */
                   1418: 
1.230     brouard  1419: int *Tvarsel; /**< Selected covariates for output */
                   1420: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1421: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1422: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1423: 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  1424: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1425: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1426: int *Tage;
1.227     brouard  1427: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1428: 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  1429: 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*/ 
                   1430: 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  1431: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1432: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1433: int **Tvard;
                   1434: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1435: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1436: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1437:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1438:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1439: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1440: double *lsurv, *lpop, *tpop;
                   1441: 
1.231     brouard  1442: #define FD 1; /* Fixed dummy covariate */
                   1443: #define FQ 2; /* Fixed quantitative covariate */
                   1444: #define FP 3; /* Fixed product covariate */
                   1445: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1446: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1447: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1448: #define VD 10; /* Varying dummy covariate */
                   1449: #define VQ 11; /* Varying quantitative covariate */
                   1450: #define VP 12; /* Varying product covariate */
                   1451: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1452: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1453: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1454: #define APFD 16; /* Age product * fixed dummy covariate */
                   1455: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1456: #define APVD 18; /* Age product * varying dummy covariate */
                   1457: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1458: 
                   1459: #define FTYPE 1; /* Fixed covariate */
                   1460: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1461: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1462: 
                   1463: struct kmodel{
                   1464:        int maintype; /* main type */
                   1465:        int subtype; /* subtype */
                   1466: };
                   1467: struct kmodel modell[NCOVMAX];
                   1468: 
1.143     brouard  1469: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1470: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1471: 
                   1472: /**************** split *************************/
                   1473: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1474: {
                   1475:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1476:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1477:   */ 
                   1478:   char *ss;                            /* pointer */
1.186     brouard  1479:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1480: 
                   1481:   l1 = strlen(path );                  /* length of path */
                   1482:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1483:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1484:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1485:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1486:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1487:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1488:     /* get current working directory */
                   1489:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1490: #ifdef WIN32
                   1491:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1492: #else
                   1493:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1494: #endif
1.126     brouard  1495:       return( GLOCK_ERROR_GETCWD );
                   1496:     }
                   1497:     /* got dirc from getcwd*/
                   1498:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1499:   } else {                             /* strip directory from path */
1.126     brouard  1500:     ss++;                              /* after this, the filename */
                   1501:     l2 = strlen( ss );                 /* length of filename */
                   1502:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1503:     strcpy( name, ss );                /* save file name */
                   1504:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1505:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1506:     printf(" DIRC2 = %s \n",dirc);
                   1507:   }
                   1508:   /* We add a separator at the end of dirc if not exists */
                   1509:   l1 = strlen( dirc );                 /* length of directory */
                   1510:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1511:     dirc[l1] =  DIRSEPARATOR;
                   1512:     dirc[l1+1] = 0; 
                   1513:     printf(" DIRC3 = %s \n",dirc);
                   1514:   }
                   1515:   ss = strrchr( name, '.' );           /* find last / */
                   1516:   if (ss >0){
                   1517:     ss++;
                   1518:     strcpy(ext,ss);                    /* save extension */
                   1519:     l1= strlen( name);
                   1520:     l2= strlen(ss)+1;
                   1521:     strncpy( finame, name, l1-l2);
                   1522:     finame[l1-l2]= 0;
                   1523:   }
                   1524: 
                   1525:   return( 0 );                         /* we're done */
                   1526: }
                   1527: 
                   1528: 
                   1529: /******************************************/
                   1530: 
                   1531: void replace_back_to_slash(char *s, char*t)
                   1532: {
                   1533:   int i;
                   1534:   int lg=0;
                   1535:   i=0;
                   1536:   lg=strlen(t);
                   1537:   for(i=0; i<= lg; i++) {
                   1538:     (s[i] = t[i]);
                   1539:     if (t[i]== '\\') s[i]='/';
                   1540:   }
                   1541: }
                   1542: 
1.132     brouard  1543: char *trimbb(char *out, char *in)
1.137     brouard  1544: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1545:   char *s;
                   1546:   s=out;
                   1547:   while (*in != '\0'){
1.137     brouard  1548:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1549:       in++;
                   1550:     }
                   1551:     *out++ = *in++;
                   1552:   }
                   1553:   *out='\0';
                   1554:   return s;
                   1555: }
                   1556: 
1.187     brouard  1557: /* char *substrchaine(char *out, char *in, char *chain) */
                   1558: /* { */
                   1559: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1560: /*   char *s, *t; */
                   1561: /*   t=in;s=out; */
                   1562: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1563: /*     *out++ = *in++; */
                   1564: /*   } */
                   1565: 
                   1566: /*   /\* *in matches *chain *\/ */
                   1567: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1568: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1569: /*   } */
                   1570: /*   in--; chain--; */
                   1571: /*   while ( (*in != '\0')){ */
                   1572: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1573: /*     *out++ = *in++; */
                   1574: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1575: /*   } */
                   1576: /*   *out='\0'; */
                   1577: /*   out=s; */
                   1578: /*   return out; */
                   1579: /* } */
                   1580: char *substrchaine(char *out, char *in, char *chain)
                   1581: {
                   1582:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1583:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1584: 
                   1585:   char *strloc;
                   1586: 
                   1587:   strcpy (out, in); 
                   1588:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1589:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1590:   if(strloc != NULL){ 
                   1591:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1592:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1593:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1594:   }
                   1595:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1596:   return out;
                   1597: }
                   1598: 
                   1599: 
1.145     brouard  1600: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1601: {
1.187     brouard  1602:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1603:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1604:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1605:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1606:   */
1.160     brouard  1607:   char *s, *t;
1.145     brouard  1608:   t=in;s=in;
                   1609:   while ((*in != occ) && (*in != '\0')){
                   1610:     *alocc++ = *in++;
                   1611:   }
                   1612:   if( *in == occ){
                   1613:     *(alocc)='\0';
                   1614:     s=++in;
                   1615:   }
                   1616:  
                   1617:   if (s == t) {/* occ not found */
                   1618:     *(alocc-(in-s))='\0';
                   1619:     in=s;
                   1620:   }
                   1621:   while ( *in != '\0'){
                   1622:     *blocc++ = *in++;
                   1623:   }
                   1624: 
                   1625:   *blocc='\0';
                   1626:   return t;
                   1627: }
1.137     brouard  1628: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1629: {
1.187     brouard  1630:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1631:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1632:      gives blocc="abcdef2ghi" and alocc="j".
                   1633:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1634:   */
                   1635:   char *s, *t;
                   1636:   t=in;s=in;
                   1637:   while (*in != '\0'){
                   1638:     while( *in == occ){
                   1639:       *blocc++ = *in++;
                   1640:       s=in;
                   1641:     }
                   1642:     *blocc++ = *in++;
                   1643:   }
                   1644:   if (s == t) /* occ not found */
                   1645:     *(blocc-(in-s))='\0';
                   1646:   else
                   1647:     *(blocc-(in-s)-1)='\0';
                   1648:   in=s;
                   1649:   while ( *in != '\0'){
                   1650:     *alocc++ = *in++;
                   1651:   }
                   1652: 
                   1653:   *alocc='\0';
                   1654:   return s;
                   1655: }
                   1656: 
1.126     brouard  1657: int nbocc(char *s, char occ)
                   1658: {
                   1659:   int i,j=0;
                   1660:   int lg=20;
                   1661:   i=0;
                   1662:   lg=strlen(s);
                   1663:   for(i=0; i<= lg; i++) {
1.234     brouard  1664:     if  (s[i] == occ ) j++;
1.126     brouard  1665:   }
                   1666:   return j;
                   1667: }
                   1668: 
1.137     brouard  1669: /* void cutv(char *u,char *v, char*t, char occ) */
                   1670: /* { */
                   1671: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1672: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1673: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1674: /*   int i,lg,j,p=0; */
                   1675: /*   i=0; */
                   1676: /*   lg=strlen(t); */
                   1677: /*   for(j=0; j<=lg-1; j++) { */
                   1678: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1679: /*   } */
1.126     brouard  1680: 
1.137     brouard  1681: /*   for(j=0; j<p; j++) { */
                   1682: /*     (u[j] = t[j]); */
                   1683: /*   } */
                   1684: /*      u[p]='\0'; */
1.126     brouard  1685: 
1.137     brouard  1686: /*    for(j=0; j<= lg; j++) { */
                   1687: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1688: /*   } */
                   1689: /* } */
1.126     brouard  1690: 
1.160     brouard  1691: #ifdef _WIN32
                   1692: char * strsep(char **pp, const char *delim)
                   1693: {
                   1694:   char *p, *q;
                   1695:          
                   1696:   if ((p = *pp) == NULL)
                   1697:     return 0;
                   1698:   if ((q = strpbrk (p, delim)) != NULL)
                   1699:   {
                   1700:     *pp = q + 1;
                   1701:     *q = '\0';
                   1702:   }
                   1703:   else
                   1704:     *pp = 0;
                   1705:   return p;
                   1706: }
                   1707: #endif
                   1708: 
1.126     brouard  1709: /********************** nrerror ********************/
                   1710: 
                   1711: void nrerror(char error_text[])
                   1712: {
                   1713:   fprintf(stderr,"ERREUR ...\n");
                   1714:   fprintf(stderr,"%s\n",error_text);
                   1715:   exit(EXIT_FAILURE);
                   1716: }
                   1717: /*********************** vector *******************/
                   1718: double *vector(int nl, int nh)
                   1719: {
                   1720:   double *v;
                   1721:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1722:   if (!v) nrerror("allocation failure in vector");
                   1723:   return v-nl+NR_END;
                   1724: }
                   1725: 
                   1726: /************************ free vector ******************/
                   1727: void free_vector(double*v, int nl, int nh)
                   1728: {
                   1729:   free((FREE_ARG)(v+nl-NR_END));
                   1730: }
                   1731: 
                   1732: /************************ivector *******************************/
                   1733: int *ivector(long nl,long nh)
                   1734: {
                   1735:   int *v;
                   1736:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1737:   if (!v) nrerror("allocation failure in ivector");
                   1738:   return v-nl+NR_END;
                   1739: }
                   1740: 
                   1741: /******************free ivector **************************/
                   1742: void free_ivector(int *v, long nl, long nh)
                   1743: {
                   1744:   free((FREE_ARG)(v+nl-NR_END));
                   1745: }
                   1746: 
                   1747: /************************lvector *******************************/
                   1748: long *lvector(long nl,long nh)
                   1749: {
                   1750:   long *v;
                   1751:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1752:   if (!v) nrerror("allocation failure in ivector");
                   1753:   return v-nl+NR_END;
                   1754: }
                   1755: 
                   1756: /******************free lvector **************************/
                   1757: void free_lvector(long *v, long nl, long nh)
                   1758: {
                   1759:   free((FREE_ARG)(v+nl-NR_END));
                   1760: }
                   1761: 
                   1762: /******************* imatrix *******************************/
                   1763: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1764:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1765: { 
                   1766:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1767:   int **m; 
                   1768:   
                   1769:   /* allocate pointers to rows */ 
                   1770:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1771:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1772:   m += NR_END; 
                   1773:   m -= nrl; 
                   1774:   
                   1775:   
                   1776:   /* allocate rows and set pointers to them */ 
                   1777:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1778:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1779:   m[nrl] += NR_END; 
                   1780:   m[nrl] -= ncl; 
                   1781:   
                   1782:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1783:   
                   1784:   /* return pointer to array of pointers to rows */ 
                   1785:   return m; 
                   1786: } 
                   1787: 
                   1788: /****************** free_imatrix *************************/
                   1789: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1790:       int **m;
                   1791:       long nch,ncl,nrh,nrl; 
                   1792:      /* free an int matrix allocated by imatrix() */ 
                   1793: { 
                   1794:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1795:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1796: } 
                   1797: 
                   1798: /******************* matrix *******************************/
                   1799: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1800: {
                   1801:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1802:   double **m;
                   1803: 
                   1804:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1805:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1806:   m += NR_END;
                   1807:   m -= nrl;
                   1808: 
                   1809:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1810:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1811:   m[nrl] += NR_END;
                   1812:   m[nrl] -= ncl;
                   1813: 
                   1814:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1815:   return m;
1.145     brouard  1816:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1817: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1818: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1819:    */
                   1820: }
                   1821: 
                   1822: /*************************free matrix ************************/
                   1823: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1824: {
                   1825:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1826:   free((FREE_ARG)(m+nrl-NR_END));
                   1827: }
                   1828: 
                   1829: /******************* ma3x *******************************/
                   1830: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1831: {
                   1832:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1833:   double ***m;
                   1834: 
                   1835:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1836:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1837:   m += NR_END;
                   1838:   m -= nrl;
                   1839: 
                   1840:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1841:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1842:   m[nrl] += NR_END;
                   1843:   m[nrl] -= ncl;
                   1844: 
                   1845:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1846: 
                   1847:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1848:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1849:   m[nrl][ncl] += NR_END;
                   1850:   m[nrl][ncl] -= nll;
                   1851:   for (j=ncl+1; j<=nch; j++) 
                   1852:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1853:   
                   1854:   for (i=nrl+1; i<=nrh; i++) {
                   1855:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1856:     for (j=ncl+1; j<=nch; j++) 
                   1857:       m[i][j]=m[i][j-1]+nlay;
                   1858:   }
                   1859:   return m; 
                   1860:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1861:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1862:   */
                   1863: }
                   1864: 
                   1865: /*************************free ma3x ************************/
                   1866: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1867: {
                   1868:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1869:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1870:   free((FREE_ARG)(m+nrl-NR_END));
                   1871: }
                   1872: 
                   1873: /*************** function subdirf ***********/
                   1874: char *subdirf(char fileres[])
                   1875: {
                   1876:   /* Caution optionfilefiname is hidden */
                   1877:   strcpy(tmpout,optionfilefiname);
                   1878:   strcat(tmpout,"/"); /* Add to the right */
                   1879:   strcat(tmpout,fileres);
                   1880:   return tmpout;
                   1881: }
                   1882: 
                   1883: /*************** function subdirf2 ***********/
                   1884: char *subdirf2(char fileres[], char *preop)
                   1885: {
1.314     brouard  1886:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1887:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1888:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1889:   /* Caution optionfilefiname is hidden */
                   1890:   strcpy(tmpout,optionfilefiname);
                   1891:   strcat(tmpout,"/");
                   1892:   strcat(tmpout,preop);
                   1893:   strcat(tmpout,fileres);
                   1894:   return tmpout;
                   1895: }
                   1896: 
                   1897: /*************** function subdirf3 ***********/
                   1898: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1899: {
                   1900:   
                   1901:   /* Caution optionfilefiname is hidden */
                   1902:   strcpy(tmpout,optionfilefiname);
                   1903:   strcat(tmpout,"/");
                   1904:   strcat(tmpout,preop);
                   1905:   strcat(tmpout,preop2);
                   1906:   strcat(tmpout,fileres);
                   1907:   return tmpout;
                   1908: }
1.213     brouard  1909:  
                   1910: /*************** function subdirfext ***********/
                   1911: char *subdirfext(char fileres[], char *preop, char *postop)
                   1912: {
                   1913:   
                   1914:   strcpy(tmpout,preop);
                   1915:   strcat(tmpout,fileres);
                   1916:   strcat(tmpout,postop);
                   1917:   return tmpout;
                   1918: }
1.126     brouard  1919: 
1.213     brouard  1920: /*************** function subdirfext3 ***********/
                   1921: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1922: {
                   1923:   
                   1924:   /* Caution optionfilefiname is hidden */
                   1925:   strcpy(tmpout,optionfilefiname);
                   1926:   strcat(tmpout,"/");
                   1927:   strcat(tmpout,preop);
                   1928:   strcat(tmpout,fileres);
                   1929:   strcat(tmpout,postop);
                   1930:   return tmpout;
                   1931: }
                   1932:  
1.162     brouard  1933: char *asc_diff_time(long time_sec, char ascdiff[])
                   1934: {
                   1935:   long sec_left, days, hours, minutes;
                   1936:   days = (time_sec) / (60*60*24);
                   1937:   sec_left = (time_sec) % (60*60*24);
                   1938:   hours = (sec_left) / (60*60) ;
                   1939:   sec_left = (sec_left) %(60*60);
                   1940:   minutes = (sec_left) /60;
                   1941:   sec_left = (sec_left) % (60);
                   1942:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1943:   return ascdiff;
                   1944: }
                   1945: 
1.126     brouard  1946: /***************** f1dim *************************/
                   1947: extern int ncom; 
                   1948: extern double *pcom,*xicom;
                   1949: extern double (*nrfunc)(double []); 
                   1950:  
                   1951: double f1dim(double x) 
                   1952: { 
                   1953:   int j; 
                   1954:   double f;
                   1955:   double *xt; 
                   1956:  
                   1957:   xt=vector(1,ncom); 
                   1958:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1959:   f=(*nrfunc)(xt); 
                   1960:   free_vector(xt,1,ncom); 
                   1961:   return f; 
                   1962: } 
                   1963: 
                   1964: /*****************brent *************************/
                   1965: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1966: {
                   1967:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1968:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1969:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1970:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1971:    * returned function value. 
                   1972:   */
1.126     brouard  1973:   int iter; 
                   1974:   double a,b,d,etemp;
1.159     brouard  1975:   double fu=0,fv,fw,fx;
1.164     brouard  1976:   double ftemp=0.;
1.126     brouard  1977:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1978:   double e=0.0; 
                   1979:  
                   1980:   a=(ax < cx ? ax : cx); 
                   1981:   b=(ax > cx ? ax : cx); 
                   1982:   x=w=v=bx; 
                   1983:   fw=fv=fx=(*f)(x); 
                   1984:   for (iter=1;iter<=ITMAX;iter++) { 
                   1985:     xm=0.5*(a+b); 
                   1986:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1987:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1988:     printf(".");fflush(stdout);
                   1989:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1990: #ifdef DEBUGBRENT
1.126     brouard  1991:     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);
                   1992:     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);
                   1993:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1994: #endif
                   1995:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1996:       *xmin=x; 
                   1997:       return fx; 
                   1998:     } 
                   1999:     ftemp=fu;
                   2000:     if (fabs(e) > tol1) { 
                   2001:       r=(x-w)*(fx-fv); 
                   2002:       q=(x-v)*(fx-fw); 
                   2003:       p=(x-v)*q-(x-w)*r; 
                   2004:       q=2.0*(q-r); 
                   2005:       if (q > 0.0) p = -p; 
                   2006:       q=fabs(q); 
                   2007:       etemp=e; 
                   2008:       e=d; 
                   2009:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2010:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2011:       else { 
1.224     brouard  2012:                                d=p/q; 
                   2013:                                u=x+d; 
                   2014:                                if (u-a < tol2 || b-u < tol2) 
                   2015:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2016:       } 
                   2017:     } else { 
                   2018:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2019:     } 
                   2020:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2021:     fu=(*f)(u); 
                   2022:     if (fu <= fx) { 
                   2023:       if (u >= x) a=x; else b=x; 
                   2024:       SHFT(v,w,x,u) 
1.183     brouard  2025:       SHFT(fv,fw,fx,fu) 
                   2026:     } else { 
                   2027:       if (u < x) a=u; else b=u; 
                   2028:       if (fu <= fw || w == x) { 
1.224     brouard  2029:                                v=w; 
                   2030:                                w=u; 
                   2031:                                fv=fw; 
                   2032:                                fw=fu; 
1.183     brouard  2033:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2034:                                v=u; 
                   2035:                                fv=fu; 
1.183     brouard  2036:       } 
                   2037:     } 
1.126     brouard  2038:   } 
                   2039:   nrerror("Too many iterations in brent"); 
                   2040:   *xmin=x; 
                   2041:   return fx; 
                   2042: } 
                   2043: 
                   2044: /****************** mnbrak ***********************/
                   2045: 
                   2046: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2047:            double (*func)(double)) 
1.183     brouard  2048: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2049: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2050: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2051: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2052:    */
1.126     brouard  2053:   double ulim,u,r,q, dum;
                   2054:   double fu; 
1.187     brouard  2055: 
                   2056:   double scale=10.;
                   2057:   int iterscale=0;
                   2058: 
                   2059:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2060:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2061: 
                   2062: 
                   2063:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2064:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2065:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2066:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2067:   /* } */
                   2068: 
1.126     brouard  2069:   if (*fb > *fa) { 
                   2070:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2071:     SHFT(dum,*fb,*fa,dum) 
                   2072:   } 
1.126     brouard  2073:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2074:   *fc=(*func)(*cx); 
1.183     brouard  2075: #ifdef DEBUG
1.224     brouard  2076:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2077:   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  2078: #endif
1.224     brouard  2079:   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  2080:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2081:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2082:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2083:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2084:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2085:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2086:       fu=(*func)(u); 
1.163     brouard  2087: #ifdef DEBUG
                   2088:       /* f(x)=A(x-u)**2+f(u) */
                   2089:       double A, fparabu; 
                   2090:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2091:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2092:       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);
                   2093:       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  2094:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2095:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2096:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2097:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2098: #endif 
1.184     brouard  2099: #ifdef MNBRAKORIGINAL
1.183     brouard  2100: #else
1.191     brouard  2101: /*       if (fu > *fc) { */
                   2102: /* #ifdef DEBUG */
                   2103: /*       printf("mnbrak4  fu > fc \n"); */
                   2104: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2105: /* #endif */
                   2106: /*     /\* 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 *\\/  *\/ */
                   2107: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2108: /*     dum=u; /\* Shifting c and u *\/ */
                   2109: /*     u = *cx; */
                   2110: /*     *cx = dum; */
                   2111: /*     dum = fu; */
                   2112: /*     fu = *fc; */
                   2113: /*     *fc =dum; */
                   2114: /*       } else { /\* end *\/ */
                   2115: /* #ifdef DEBUG */
                   2116: /*       printf("mnbrak3  fu < fc \n"); */
                   2117: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2118: /* #endif */
                   2119: /*     dum=u; /\* Shifting c and u *\/ */
                   2120: /*     u = *cx; */
                   2121: /*     *cx = dum; */
                   2122: /*     dum = fu; */
                   2123: /*     fu = *fc; */
                   2124: /*     *fc =dum; */
                   2125: /*       } */
1.224     brouard  2126: #ifdef DEBUGMNBRAK
                   2127:                 double A, fparabu; 
                   2128:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2129:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2130:      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);
                   2131:      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  2132: #endif
1.191     brouard  2133:       dum=u; /* Shifting c and u */
                   2134:       u = *cx;
                   2135:       *cx = dum;
                   2136:       dum = fu;
                   2137:       fu = *fc;
                   2138:       *fc =dum;
1.183     brouard  2139: #endif
1.162     brouard  2140:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2141: #ifdef DEBUG
1.224     brouard  2142:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2143:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2144: #endif
1.126     brouard  2145:       fu=(*func)(u); 
                   2146:       if (fu < *fc) { 
1.183     brouard  2147: #ifdef DEBUG
1.224     brouard  2148:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2149:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2150: #endif
                   2151:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2152:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2153: #ifdef DEBUG
                   2154:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2155: #endif
                   2156:       } 
1.162     brouard  2157:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2158: #ifdef DEBUG
1.224     brouard  2159:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2160:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2161: #endif
1.126     brouard  2162:       u=ulim; 
                   2163:       fu=(*func)(u); 
1.183     brouard  2164:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2165: #ifdef DEBUG
1.224     brouard  2166:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2167:       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  2168: #endif
1.126     brouard  2169:       u=(*cx)+GOLD*(*cx-*bx); 
                   2170:       fu=(*func)(u); 
1.224     brouard  2171: #ifdef DEBUG
                   2172:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2173:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2174: #endif
1.183     brouard  2175:     } /* end tests */
1.126     brouard  2176:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2177:     SHFT(*fa,*fb,*fc,fu) 
                   2178: #ifdef DEBUG
1.224     brouard  2179:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2180:       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  2181: #endif
                   2182:   } /* 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  2183: } 
                   2184: 
                   2185: /*************** linmin ************************/
1.162     brouard  2186: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2187: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2188: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2189: the value of func at the returned location p . This is actually all accomplished by calling the
                   2190: routines mnbrak and brent .*/
1.126     brouard  2191: int ncom; 
                   2192: double *pcom,*xicom;
                   2193: double (*nrfunc)(double []); 
                   2194:  
1.224     brouard  2195: #ifdef LINMINORIGINAL
1.126     brouard  2196: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2197: #else
                   2198: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2199: #endif
1.126     brouard  2200: { 
                   2201:   double brent(double ax, double bx, double cx, 
                   2202:               double (*f)(double), double tol, double *xmin); 
                   2203:   double f1dim(double x); 
                   2204:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2205:              double *fc, double (*func)(double)); 
                   2206:   int j; 
                   2207:   double xx,xmin,bx,ax; 
                   2208:   double fx,fb,fa;
1.187     brouard  2209: 
1.203     brouard  2210: #ifdef LINMINORIGINAL
                   2211: #else
                   2212:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2213: #endif
                   2214:   
1.126     brouard  2215:   ncom=n; 
                   2216:   pcom=vector(1,n); 
                   2217:   xicom=vector(1,n); 
                   2218:   nrfunc=func; 
                   2219:   for (j=1;j<=n;j++) { 
                   2220:     pcom[j]=p[j]; 
1.202     brouard  2221:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2222:   } 
1.187     brouard  2223: 
1.203     brouard  2224: #ifdef LINMINORIGINAL
                   2225:   xx=1.;
                   2226: #else
                   2227:   axs=0.0;
                   2228:   xxs=1.;
                   2229:   do{
                   2230:     xx= xxs;
                   2231: #endif
1.187     brouard  2232:     ax=0.;
                   2233:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2234:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2235:     /* 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))   */
                   2236:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2237:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2238:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2239:     /* 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  2240: #ifdef LINMINORIGINAL
                   2241: #else
                   2242:     if (fx != fx){
1.224     brouard  2243:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2244:                        printf("|");
                   2245:                        fprintf(ficlog,"|");
1.203     brouard  2246: #ifdef DEBUGLINMIN
1.224     brouard  2247:                        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  2248: #endif
                   2249:     }
1.224     brouard  2250:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2251: #endif
                   2252:   
1.191     brouard  2253: #ifdef DEBUGLINMIN
                   2254:   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  2255:   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  2256: #endif
1.224     brouard  2257: #ifdef LINMINORIGINAL
                   2258: #else
                   2259:        if(fb == fx){ /* Flat function in the direction */
                   2260:                xmin=xx;
                   2261:     *flat=1;
                   2262:        }else{
                   2263:     *flat=0;
                   2264: #endif
                   2265:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2266:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2267:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2268:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2269:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2270:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2271: #ifdef DEBUG
1.224     brouard  2272:   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);
                   2273:   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);
                   2274: #endif
                   2275: #ifdef LINMINORIGINAL
                   2276: #else
                   2277:                        }
1.126     brouard  2278: #endif
1.191     brouard  2279: #ifdef DEBUGLINMIN
                   2280:   printf("linmin end ");
1.202     brouard  2281:   fprintf(ficlog,"linmin end ");
1.191     brouard  2282: #endif
1.126     brouard  2283:   for (j=1;j<=n;j++) { 
1.203     brouard  2284: #ifdef LINMINORIGINAL
                   2285:     xi[j] *= xmin; 
                   2286: #else
                   2287: #ifdef DEBUGLINMIN
                   2288:     if(xxs <1.0)
                   2289:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2290: #endif
                   2291:     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) */
                   2292: #ifdef DEBUGLINMIN
                   2293:     if(xxs <1.0)
                   2294:       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 );
                   2295: #endif
                   2296: #endif
1.187     brouard  2297:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2298:   } 
1.191     brouard  2299: #ifdef DEBUGLINMIN
1.203     brouard  2300:   printf("\n");
1.191     brouard  2301:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2302:   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  2303:   for (j=1;j<=n;j++) { 
1.202     brouard  2304:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2305:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2306:     if(j % ncovmodel == 0){
1.191     brouard  2307:       printf("\n");
1.202     brouard  2308:       fprintf(ficlog,"\n");
                   2309:     }
1.191     brouard  2310:   }
1.203     brouard  2311: #else
1.191     brouard  2312: #endif
1.126     brouard  2313:   free_vector(xicom,1,n); 
                   2314:   free_vector(pcom,1,n); 
                   2315: } 
                   2316: 
                   2317: 
                   2318: /*************** powell ************************/
1.162     brouard  2319: /*
                   2320: Minimization of a function func of n variables. Input consists of an initial starting point
                   2321: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2322: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2323: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2324: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2325: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2326:  */
1.224     brouard  2327: #ifdef LINMINORIGINAL
                   2328: #else
                   2329:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2330:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2331: #endif
1.126     brouard  2332: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2333:            double (*func)(double [])) 
                   2334: { 
1.224     brouard  2335: #ifdef LINMINORIGINAL
                   2336:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2337:              double (*func)(double [])); 
1.224     brouard  2338: #else 
1.241     brouard  2339:  void linmin(double p[], double xi[], int n, double *fret,
                   2340:             double (*func)(double []),int *flat); 
1.224     brouard  2341: #endif
1.239     brouard  2342:  int i,ibig,j,jk,k; 
1.126     brouard  2343:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2344:   double directest;
1.126     brouard  2345:   double fp,fptt;
                   2346:   double *xits;
                   2347:   int niterf, itmp;
1.224     brouard  2348: #ifdef LINMINORIGINAL
                   2349: #else
                   2350: 
                   2351:   flatdir=ivector(1,n); 
                   2352:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2353: #endif
1.126     brouard  2354: 
                   2355:   pt=vector(1,n); 
                   2356:   ptt=vector(1,n); 
                   2357:   xit=vector(1,n); 
                   2358:   xits=vector(1,n); 
                   2359:   *fret=(*func)(p); 
                   2360:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2361:   rcurr_time = time(NULL);  
1.126     brouard  2362:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2363:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2364:     ibig=0; 
                   2365:     del=0.0; 
1.157     brouard  2366:     rlast_time=rcurr_time;
                   2367:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2368:     rcurr_time = time(NULL);  
                   2369:     curr_time = *localtime(&rcurr_time);
                   2370:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2371:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2372: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2373:     for (i=1;i<=n;i++) {
1.126     brouard  2374:       fprintf(ficrespow," %.12lf", p[i]);
                   2375:     }
1.239     brouard  2376:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2377:     printf("\n#model=  1      +     age ");
                   2378:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2379:     if(nagesqr==1){
1.241     brouard  2380:        printf("  + age*age  ");
                   2381:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2382:     }
                   2383:     for(j=1;j <=ncovmodel-2;j++){
                   2384:       if(Typevar[j]==0) {
                   2385:        printf("  +      V%d  ",Tvar[j]);
                   2386:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2387:       }else if(Typevar[j]==1) {
                   2388:        printf("  +    V%d*age ",Tvar[j]);
                   2389:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2390:       }else if(Typevar[j]==2) {
                   2391:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2392:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2393:       }
                   2394:     }
1.126     brouard  2395:     printf("\n");
1.239     brouard  2396: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2397: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2398:     fprintf(ficlog,"\n");
1.239     brouard  2399:     for(i=1,jk=1; i <=nlstate; i++){
                   2400:       for(k=1; k <=(nlstate+ndeath); k++){
                   2401:        if (k != i) {
                   2402:          printf("%d%d ",i,k);
                   2403:          fprintf(ficlog,"%d%d ",i,k);
                   2404:          for(j=1; j <=ncovmodel; j++){
                   2405:            printf("%12.7f ",p[jk]);
                   2406:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2407:            jk++; 
                   2408:          }
                   2409:          printf("\n");
                   2410:          fprintf(ficlog,"\n");
                   2411:        }
                   2412:       }
                   2413:     }
1.241     brouard  2414:     if(*iter <=3 && *iter >1){
1.157     brouard  2415:       tml = *localtime(&rcurr_time);
                   2416:       strcpy(strcurr,asctime(&tml));
                   2417:       rforecast_time=rcurr_time; 
1.126     brouard  2418:       itmp = strlen(strcurr);
                   2419:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2420:        strcurr[itmp-1]='\0';
1.162     brouard  2421:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2422:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2423:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2424:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2425:        forecast_time = *localtime(&rforecast_time);
                   2426:        strcpy(strfor,asctime(&forecast_time));
                   2427:        itmp = strlen(strfor);
                   2428:        if(strfor[itmp-1]=='\n')
                   2429:          strfor[itmp-1]='\0';
                   2430:        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);
                   2431:        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  2432:       }
                   2433:     }
1.187     brouard  2434:     for (i=1;i<=n;i++) { /* For each direction i */
                   2435:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2436:       fptt=(*fret); 
                   2437: #ifdef DEBUG
1.203     brouard  2438:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2439:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2440: #endif
1.203     brouard  2441:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2442:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2443: #ifdef LINMINORIGINAL
1.188     brouard  2444:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2445: #else
                   2446:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2447:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2448: #endif
                   2449:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2450:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2451:                                /* because that direction will be replaced unless the gain del is small */
                   2452:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2453:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2454:                                /* with the new direction. */
                   2455:                                del=fabs(fptt-(*fret)); 
                   2456:                                ibig=i; 
1.126     brouard  2457:       } 
                   2458: #ifdef DEBUG
                   2459:       printf("%d %.12e",i,(*fret));
                   2460:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2461:       for (j=1;j<=n;j++) {
1.224     brouard  2462:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2463:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2464:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2465:       }
                   2466:       for(j=1;j<=n;j++) {
1.225     brouard  2467:                                printf(" p(%d)=%.12e",j,p[j]);
                   2468:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2469:       }
                   2470:       printf("\n");
                   2471:       fprintf(ficlog,"\n");
                   2472: #endif
1.187     brouard  2473:     } /* end loop on each direction i */
                   2474:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2475:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2476:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2477:       for(j=1;j<=n;j++) {
1.302     brouard  2478:        if(flatdir[j] >0){
                   2479:          printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2480:          fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2481:        }
                   2482:        /* printf("\n"); */
                   2483:        /* fprintf(ficlog,"\n"); */
                   2484:       }
1.243     brouard  2485:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2486:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2487:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2488:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2489:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2490:       /* decreased of more than 3.84  */
                   2491:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2492:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2493:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2494:                        
1.188     brouard  2495:       /* Starting the program with initial values given by a former maximization will simply change */
                   2496:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2497:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2498:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2499: #ifdef DEBUG
                   2500:       int k[2],l;
                   2501:       k[0]=1;
                   2502:       k[1]=-1;
                   2503:       printf("Max: %.12e",(*func)(p));
                   2504:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2505:       for (j=1;j<=n;j++) {
                   2506:        printf(" %.12e",p[j]);
                   2507:        fprintf(ficlog," %.12e",p[j]);
                   2508:       }
                   2509:       printf("\n");
                   2510:       fprintf(ficlog,"\n");
                   2511:       for(l=0;l<=1;l++) {
                   2512:        for (j=1;j<=n;j++) {
                   2513:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2514:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2515:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2516:        }
                   2517:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2518:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2519:       }
                   2520: #endif
                   2521: 
1.224     brouard  2522: #ifdef LINMINORIGINAL
                   2523: #else
                   2524:       free_ivector(flatdir,1,n); 
                   2525: #endif
1.126     brouard  2526:       free_vector(xit,1,n); 
                   2527:       free_vector(xits,1,n); 
                   2528:       free_vector(ptt,1,n); 
                   2529:       free_vector(pt,1,n); 
                   2530:       return; 
1.192     brouard  2531:     } /* enough precision */ 
1.240     brouard  2532:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2533:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2534:       ptt[j]=2.0*p[j]-pt[j]; 
                   2535:       xit[j]=p[j]-pt[j]; 
                   2536:       pt[j]=p[j]; 
                   2537:     } 
1.181     brouard  2538:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2539: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2540:                if (*iter <=4) {
1.225     brouard  2541: #else
                   2542: #endif
1.224     brouard  2543: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2544: #else
1.161     brouard  2545:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2546: #endif
1.162     brouard  2547:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2548:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2549:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2550:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2551:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2552:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2553:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2554:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2555:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2556:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2557:       /* mu² and del² are equal when f3=f1 */
                   2558:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2559:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2560:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2561:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2562: #ifdef NRCORIGINAL
                   2563:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2564: #else
                   2565:       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  2566:       t= t- del*SQR(fp-fptt);
1.183     brouard  2567: #endif
1.202     brouard  2568:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2569: #ifdef DEBUG
1.181     brouard  2570:       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);
                   2571:       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  2572:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2573:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2574:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2575:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2576:       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);
                   2577:       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);
                   2578: #endif
1.183     brouard  2579: #ifdef POWELLORIGINAL
                   2580:       if (t < 0.0) { /* Then we use it for new direction */
                   2581: #else
1.182     brouard  2582:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2583:                                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  2584:         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  2585:         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  2586:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2587:       } 
1.181     brouard  2588:       if (directest < 0.0) { /* Then we use it for new direction */
                   2589: #endif
1.191     brouard  2590: #ifdef DEBUGLINMIN
1.234     brouard  2591:        printf("Before linmin in direction P%d-P0\n",n);
                   2592:        for (j=1;j<=n;j++) {
                   2593:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2594:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2595:          if(j % ncovmodel == 0){
                   2596:            printf("\n");
                   2597:            fprintf(ficlog,"\n");
                   2598:          }
                   2599:        }
1.224     brouard  2600: #endif
                   2601: #ifdef LINMINORIGINAL
1.234     brouard  2602:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2603: #else
1.234     brouard  2604:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2605:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2606: #endif
1.234     brouard  2607:        
1.191     brouard  2608: #ifdef DEBUGLINMIN
1.234     brouard  2609:        for (j=1;j<=n;j++) { 
                   2610:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2611:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2612:          if(j % ncovmodel == 0){
                   2613:            printf("\n");
                   2614:            fprintf(ficlog,"\n");
                   2615:          }
                   2616:        }
1.224     brouard  2617: #endif
1.234     brouard  2618:        for (j=1;j<=n;j++) { 
                   2619:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2620:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2621:        }
1.224     brouard  2622: #ifdef LINMINORIGINAL
                   2623: #else
1.234     brouard  2624:        for (j=1, flatd=0;j<=n;j++) {
                   2625:          if(flatdir[j]>0)
                   2626:            flatd++;
                   2627:        }
                   2628:        if(flatd >0){
1.255     brouard  2629:          printf("%d flat directions: ",flatd);
                   2630:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2631:          for (j=1;j<=n;j++) { 
                   2632:            if(flatdir[j]>0){
                   2633:              printf("%d ",j);
                   2634:              fprintf(ficlog,"%d ",j);
                   2635:            }
                   2636:          }
                   2637:          printf("\n");
                   2638:          fprintf(ficlog,"\n");
                   2639:        }
1.191     brouard  2640: #endif
1.234     brouard  2641:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2642:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2643:        
1.126     brouard  2644: #ifdef DEBUG
1.234     brouard  2645:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2646:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2647:        for(j=1;j<=n;j++){
                   2648:          printf(" %lf",xit[j]);
                   2649:          fprintf(ficlog," %lf",xit[j]);
                   2650:        }
                   2651:        printf("\n");
                   2652:        fprintf(ficlog,"\n");
1.126     brouard  2653: #endif
1.192     brouard  2654:       } /* end of t or directest negative */
1.224     brouard  2655: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2656: #else
1.234     brouard  2657:       } /* end if (fptt < fp)  */
1.192     brouard  2658: #endif
1.225     brouard  2659: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2660:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2661: #else
1.224     brouard  2662: #endif
1.234     brouard  2663:                } /* loop iteration */ 
1.126     brouard  2664: } 
1.234     brouard  2665:   
1.126     brouard  2666: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2667:   
1.235     brouard  2668:   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  2669:   {
1.279     brouard  2670:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2671:      *   (and selected quantitative values in nres)
                   2672:      *  by left multiplying the unit
                   2673:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2674:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2675:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2676:      * or prevalence in state 1, prevalence in state 2, 0
                   2677:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2678:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2679:      * Output is prlim.
                   2680:      * Initial matrix pimij 
                   2681:      */
1.206     brouard  2682:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2683:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2684:   /*  0,                   0                  , 1} */
                   2685:   /*
                   2686:    * and after some iteration: */
                   2687:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2688:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2689:   /*  0,                   0                  , 1} */
                   2690:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2691:   /* {0.51571254859325999, 0.4842874514067399, */
                   2692:   /*  0.51326036147820708, 0.48673963852179264} */
                   2693:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2694:     
1.126     brouard  2695:   int i, ii,j,k;
1.209     brouard  2696:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2697:   /* double **matprod2(); */ /* test */
1.218     brouard  2698:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2699:   double **newm;
1.209     brouard  2700:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2701:   int ncvloop=0;
1.288     brouard  2702:   int first=0;
1.169     brouard  2703:   
1.209     brouard  2704:   min=vector(1,nlstate);
                   2705:   max=vector(1,nlstate);
                   2706:   meandiff=vector(1,nlstate);
                   2707: 
1.218     brouard  2708:        /* Starting with matrix unity */
1.126     brouard  2709:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2710:     for (j=1;j<=nlstate+ndeath;j++){
                   2711:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2712:     }
1.169     brouard  2713:   
                   2714:   cov[1]=1.;
                   2715:   
                   2716:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2717:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2718:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2719:     ncvloop++;
1.126     brouard  2720:     newm=savm;
                   2721:     /* Covariates have to be included here again */
1.138     brouard  2722:     cov[2]=agefin;
1.187     brouard  2723:     if(nagesqr==1)
                   2724:       cov[3]= agefin*agefin;;
1.234     brouard  2725:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2726:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2727:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2728:       /* 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  2729:     }
                   2730:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2731:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2732:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2733:       /* 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  2734:     }
1.237     brouard  2735:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2736:       if(Dummy[Tvar[Tage[k]]]){
                   2737:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2738:       } else{
1.235     brouard  2739:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2740:       }
1.235     brouard  2741:       /* 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  2742:     }
1.237     brouard  2743:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2744:       /* 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  2745:       if(Dummy[Tvard[k][1]==0]){
                   2746:        if(Dummy[Tvard[k][2]==0]){
                   2747:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2748:        }else{
                   2749:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2750:        }
                   2751:       }else{
                   2752:        if(Dummy[Tvard[k][2]==0]){
                   2753:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2754:        }else{
                   2755:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2756:        }
                   2757:       }
1.234     brouard  2758:     }
1.138     brouard  2759:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2760:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2761:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2762:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2763:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2764:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2765:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2766:     
1.126     brouard  2767:     savm=oldm;
                   2768:     oldm=newm;
1.209     brouard  2769: 
                   2770:     for(j=1; j<=nlstate; j++){
                   2771:       max[j]=0.;
                   2772:       min[j]=1.;
                   2773:     }
                   2774:     for(i=1;i<=nlstate;i++){
                   2775:       sumnew=0;
                   2776:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2777:       for(j=1; j<=nlstate; j++){ 
                   2778:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2779:        max[j]=FMAX(max[j],prlim[i][j]);
                   2780:        min[j]=FMIN(min[j],prlim[i][j]);
                   2781:       }
                   2782:     }
                   2783: 
1.126     brouard  2784:     maxmax=0.;
1.209     brouard  2785:     for(j=1; j<=nlstate; j++){
                   2786:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2787:       maxmax=FMAX(maxmax,meandiff[j]);
                   2788:       /* 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  2789:     } /* j loop */
1.203     brouard  2790:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2791:     /* 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  2792:     if(maxmax < ftolpl){
1.209     brouard  2793:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2794:       free_vector(min,1,nlstate);
                   2795:       free_vector(max,1,nlstate);
                   2796:       free_vector(meandiff,1,nlstate);
1.126     brouard  2797:       return prlim;
                   2798:     }
1.288     brouard  2799:   } /* agefin loop */
1.208     brouard  2800:     /* After some age loop it doesn't converge */
1.288     brouard  2801:   if(!first){
                   2802:     first=1;
                   2803:     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);
                   2804:   }
                   2805:   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);
                   2806: 
1.209     brouard  2807:   /* 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); */
                   2808:   free_vector(min,1,nlstate);
                   2809:   free_vector(max,1,nlstate);
                   2810:   free_vector(meandiff,1,nlstate);
1.208     brouard  2811:   
1.169     brouard  2812:   return prlim; /* should not reach here */
1.126     brouard  2813: }
                   2814: 
1.217     brouard  2815: 
                   2816:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2817: 
1.218     brouard  2818:  /* 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) */
                   2819:  /* 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  2820:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2821: {
1.264     brouard  2822:   /* 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  2823:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2824:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2825:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2826:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2827:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2828:   /* Initial matrix pimij */
                   2829:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2830:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2831:   /*  0,                   0                  , 1} */
                   2832:   /*
                   2833:    * and after some iteration: */
                   2834:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2835:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2836:   /*  0,                   0                  , 1} */
                   2837:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2838:   /* {0.51571254859325999, 0.4842874514067399, */
                   2839:   /*  0.51326036147820708, 0.48673963852179264} */
                   2840:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2841: 
                   2842:   int i, ii,j,k;
1.247     brouard  2843:   int first=0;
1.217     brouard  2844:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2845:   /* double **matprod2(); */ /* test */
                   2846:   double **out, cov[NCOVMAX+1], **bmij();
                   2847:   double **newm;
1.218     brouard  2848:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2849:   double        **oldm, **savm;  /* for use */
                   2850: 
1.217     brouard  2851:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2852:   int ncvloop=0;
                   2853:   
                   2854:   min=vector(1,nlstate);
                   2855:   max=vector(1,nlstate);
                   2856:   meandiff=vector(1,nlstate);
                   2857: 
1.266     brouard  2858:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2859:   oldm=oldms; savm=savms;
                   2860:   
                   2861:   /* Starting with matrix unity */
                   2862:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2863:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2864:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2865:     }
                   2866:   
                   2867:   cov[1]=1.;
                   2868:   
                   2869:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2870:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2871:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2872:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2873:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2874:     ncvloop++;
1.218     brouard  2875:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2876:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2877:     /* Covariates have to be included here again */
                   2878:     cov[2]=agefin;
                   2879:     if(nagesqr==1)
                   2880:       cov[3]= agefin*agefin;;
1.242     brouard  2881:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2882:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2883:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2884:       /* 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  2885:     }
                   2886:     /* for (k=1; k<=cptcovn;k++) { */
                   2887:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2888:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2889:     /*   /\* 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])]); *\/ */
                   2890:     /* } */
                   2891:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2892:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2893:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2894:       /* 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]); */
                   2895:     }
                   2896:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2897:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2898:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2899:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2900:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2901:       if(Dummy[Tvar[Tage[k]]]){
                   2902:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2903:       } else{
                   2904:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2905:       }
                   2906:       /* 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]); */
                   2907:     }
                   2908:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2909:       /* 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]); */
                   2910:       if(Dummy[Tvard[k][1]==0]){
                   2911:        if(Dummy[Tvard[k][2]==0]){
                   2912:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2913:        }else{
                   2914:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2915:        }
                   2916:       }else{
                   2917:        if(Dummy[Tvard[k][2]==0]){
                   2918:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2919:        }else{
                   2920:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2921:        }
                   2922:       }
1.217     brouard  2923:     }
                   2924:     
                   2925:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2926:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2927:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2928:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2929:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2930:                /* ij should be linked to the correct index of cov */
                   2931:                /* age and covariate values ij are in 'cov', but we need to pass
                   2932:                 * ij for the observed prevalence at age and status and covariate
                   2933:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2934:                 */
                   2935:     /* 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 *\/ */
                   2936:     /* 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 *\/ */
                   2937:     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  2938:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2939:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2940:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2941:     /*         printf("%d newm= ",i); */
                   2942:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2943:     /*           printf("%f ",newm[i][j]); */
                   2944:     /*         } */
                   2945:     /*         printf("oldm * "); */
                   2946:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2947:     /*           printf("%f ",oldm[i][j]); */
                   2948:     /*         } */
1.268     brouard  2949:     /*         printf(" bmmij "); */
1.266     brouard  2950:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2951:     /*           printf("%f ",pmmij[i][j]); */
                   2952:     /*         } */
                   2953:     /*         printf("\n"); */
                   2954:     /*   } */
                   2955:     /* } */
1.217     brouard  2956:     savm=oldm;
                   2957:     oldm=newm;
1.266     brouard  2958: 
1.217     brouard  2959:     for(j=1; j<=nlstate; j++){
                   2960:       max[j]=0.;
                   2961:       min[j]=1.;
                   2962:     }
                   2963:     for(j=1; j<=nlstate; j++){ 
                   2964:       for(i=1;i<=nlstate;i++){
1.234     brouard  2965:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2966:        bprlim[i][j]= newm[i][j];
                   2967:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2968:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2969:       }
                   2970:     }
1.218     brouard  2971:                
1.217     brouard  2972:     maxmax=0.;
                   2973:     for(i=1; i<=nlstate; i++){
                   2974:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2975:       maxmax=FMAX(maxmax,meandiff[i]);
                   2976:       /* 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  2977:     } /* i loop */
1.217     brouard  2978:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2979:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2980:     if(maxmax < ftolpl){
1.220     brouard  2981:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2982:       free_vector(min,1,nlstate);
                   2983:       free_vector(max,1,nlstate);
                   2984:       free_vector(meandiff,1,nlstate);
                   2985:       return bprlim;
                   2986:     }
1.288     brouard  2987:   } /* agefin loop */
1.217     brouard  2988:     /* After some age loop it doesn't converge */
1.288     brouard  2989:   if(!first){
1.247     brouard  2990:     first=1;
                   2991:     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\
                   2992: 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);
                   2993:   }
                   2994:   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  2995: 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);
                   2996:   /* 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); */
                   2997:   free_vector(min,1,nlstate);
                   2998:   free_vector(max,1,nlstate);
                   2999:   free_vector(meandiff,1,nlstate);
                   3000:   
                   3001:   return bprlim; /* should not reach here */
                   3002: }
                   3003: 
1.126     brouard  3004: /*************** transition probabilities ***************/ 
                   3005: 
                   3006: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3007: {
1.138     brouard  3008:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3009:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3010:      model to the ncovmodel covariates (including constant and age).
                   3011:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3012:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3013:      ncth covariate in the global vector x is given by the formula:
                   3014:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3015:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3016:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3017:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3018:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3019:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3020:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3021:   */
                   3022:   double s1, lnpijopii;
1.126     brouard  3023:   /*double t34;*/
1.164     brouard  3024:   int i,j, nc, ii, jj;
1.126     brouard  3025: 
1.223     brouard  3026:   for(i=1; i<= nlstate; i++){
                   3027:     for(j=1; j<i;j++){
                   3028:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3029:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3030:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3031:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3032:       }
                   3033:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3034:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3035:     }
                   3036:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3037:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3038:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3039:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3040:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3041:       }
                   3042:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3043:     }
                   3044:   }
1.218     brouard  3045:   
1.223     brouard  3046:   for(i=1; i<= nlstate; i++){
                   3047:     s1=0;
                   3048:     for(j=1; j<i; j++){
                   3049:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3050:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3051:     }
                   3052:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3053:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3054:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3055:     }
                   3056:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3057:     ps[i][i]=1./(s1+1.);
                   3058:     /* Computing other pijs */
                   3059:     for(j=1; j<i; j++)
                   3060:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3061:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3062:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3063:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3064:   } /* end i */
1.218     brouard  3065:   
1.223     brouard  3066:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3067:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3068:       ps[ii][jj]=0;
                   3069:       ps[ii][ii]=1;
                   3070:     }
                   3071:   }
1.294     brouard  3072: 
                   3073: 
1.223     brouard  3074:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3075:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3076:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3077:   /*   } */
                   3078:   /*   printf("\n "); */
                   3079:   /* } */
                   3080:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3081:   /*
                   3082:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3083:                goto end;*/
1.266     brouard  3084:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3085: }
                   3086: 
1.218     brouard  3087: /*************** backward transition probabilities ***************/ 
                   3088: 
                   3089:  /* 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 ) */
                   3090: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3091:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3092: {
1.302     brouard  3093:   /* 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  3094:    * 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  3095:    */
1.218     brouard  3096:   int i, ii, j,k;
1.222     brouard  3097:   
                   3098:   double **out, **pmij();
                   3099:   double sumnew=0.;
1.218     brouard  3100:   double agefin;
1.292     brouard  3101:   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  3102:   double **dnewm, **dsavm, **doldm;
                   3103:   double **bbmij;
                   3104:   
1.218     brouard  3105:   doldm=ddoldms; /* global pointers */
1.222     brouard  3106:   dnewm=ddnewms;
                   3107:   dsavm=ddsavms;
                   3108:   
                   3109:   agefin=cov[2];
1.268     brouard  3110:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3111:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3112:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3113:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3114: 
                   3115:   /* P_x */
1.266     brouard  3116:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3117:   /* outputs pmmij which is a stochastic matrix in row */
                   3118: 
                   3119:   /* Diag(w_x) */
1.292     brouard  3120:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3121:   sumnew=0.;
1.269     brouard  3122:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3123:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3124:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3125:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3126:   }
                   3127:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3128:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3129:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3130:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3131:     }
                   3132:   }else{
                   3133:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3134:       for (j=1;j<=nlstate+ndeath;j++)
                   3135:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3136:     }
                   3137:     /* if(sumnew <0.9){ */
                   3138:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3139:     /* } */
                   3140:   }
                   3141:   k3=0.0;  /* We put the last diagonal to 0 */
                   3142:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3143:       doldm[ii][ii]= k3;
                   3144:   }
                   3145:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3146:   
1.292     brouard  3147:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3148:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3149: 
1.292     brouard  3150:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3151:   /* 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  3152:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3153:     sumnew=0.;
1.222     brouard  3154:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3155:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3156:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3157:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3158:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3159:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3160:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3161:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3162:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3163:        /* }else */
1.268     brouard  3164:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3165:     } /*End ii */
                   3166:   } /* 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 */
                   3167: 
1.292     brouard  3168:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3169:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3170:   /* end bmij */
1.266     brouard  3171:   return ps; /*pointer is unchanged */
1.218     brouard  3172: }
1.217     brouard  3173: /*************** transition probabilities ***************/ 
                   3174: 
1.218     brouard  3175: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3176: {
                   3177:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3178:      computes the probability to be observed in state j being in state i by appying the
                   3179:      model to the ncovmodel covariates (including constant and age).
                   3180:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3181:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3182:      ncth covariate in the global vector x is given by the formula:
                   3183:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3184:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3185:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3186:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3187:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3188:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3189:   */
                   3190:   double s1, lnpijopii;
                   3191:   /*double t34;*/
                   3192:   int i,j, nc, ii, jj;
                   3193: 
1.234     brouard  3194:   for(i=1; i<= nlstate; i++){
                   3195:     for(j=1; j<i;j++){
                   3196:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3197:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3198:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3199:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3200:       }
                   3201:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3202:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3203:     }
                   3204:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3205:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3206:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3207:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3208:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3209:       }
                   3210:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3211:     }
                   3212:   }
                   3213:   
                   3214:   for(i=1; i<= nlstate; i++){
                   3215:     s1=0;
                   3216:     for(j=1; j<i; j++){
                   3217:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3218:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3219:     }
                   3220:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3221:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3222:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3223:     }
                   3224:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3225:     ps[i][i]=1./(s1+1.);
                   3226:     /* Computing other pijs */
                   3227:     for(j=1; j<i; j++)
                   3228:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3229:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3230:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3231:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3232:   } /* end i */
                   3233:   
                   3234:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3235:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3236:       ps[ii][jj]=0;
                   3237:       ps[ii][ii]=1;
                   3238:     }
                   3239:   }
1.296     brouard  3240:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3241:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3242:     s1=0.;
                   3243:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3244:       s1+=ps[ii][jj];
                   3245:     }
                   3246:     for(ii=1; ii<= nlstate; ii++){
                   3247:       ps[ii][jj]=ps[ii][jj]/s1;
                   3248:     }
                   3249:   }
                   3250:   /* Transposition */
                   3251:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3252:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3253:       s1=ps[ii][jj];
                   3254:       ps[ii][jj]=ps[jj][ii];
                   3255:       ps[jj][ii]=s1;
                   3256:     }
                   3257:   }
                   3258:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3259:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3260:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3261:   /*   } */
                   3262:   /*   printf("\n "); */
                   3263:   /* } */
                   3264:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3265:   /*
                   3266:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3267:     goto end;*/
                   3268:   return ps;
1.217     brouard  3269: }
                   3270: 
                   3271: 
1.126     brouard  3272: /**************** Product of 2 matrices ******************/
                   3273: 
1.145     brouard  3274: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3275: {
                   3276:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3277:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3278:   /* in, b, out are matrice of pointers which should have been initialized 
                   3279:      before: only the contents of out is modified. The function returns
                   3280:      a pointer to pointers identical to out */
1.145     brouard  3281:   int i, j, k;
1.126     brouard  3282:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3283:     for(k=ncolol; k<=ncoloh; k++){
                   3284:       out[i][k]=0.;
                   3285:       for(j=ncl; j<=nch; j++)
                   3286:        out[i][k] +=in[i][j]*b[j][k];
                   3287:     }
1.126     brouard  3288:   return out;
                   3289: }
                   3290: 
                   3291: 
                   3292: /************* Higher Matrix Product ***************/
                   3293: 
1.235     brouard  3294: 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  3295: {
1.218     brouard  3296:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3297:      'nhstepm*hstepm*stepm' months (i.e. until
                   3298:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3299:      nhstepm*hstepm matrices. 
                   3300:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3301:      (typically every 2 years instead of every month which is too big 
                   3302:      for the memory).
                   3303:      Model is determined by parameters x and covariates have to be 
                   3304:      included manually here. 
                   3305: 
                   3306:      */
                   3307: 
                   3308:   int i, j, d, h, k;
1.131     brouard  3309:   double **out, cov[NCOVMAX+1];
1.126     brouard  3310:   double **newm;
1.187     brouard  3311:   double agexact;
1.214     brouard  3312:   double agebegin, ageend;
1.126     brouard  3313: 
                   3314:   /* Hstepm could be zero and should return the unit matrix */
                   3315:   for (i=1;i<=nlstate+ndeath;i++)
                   3316:     for (j=1;j<=nlstate+ndeath;j++){
                   3317:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3318:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3319:     }
                   3320:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3321:   for(h=1; h <=nhstepm; h++){
                   3322:     for(d=1; d <=hstepm; d++){
                   3323:       newm=savm;
                   3324:       /* Covariates have to be included here again */
                   3325:       cov[1]=1.;
1.214     brouard  3326:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3327:       cov[2]=agexact;
                   3328:       if(nagesqr==1)
1.227     brouard  3329:        cov[3]= agexact*agexact;
1.235     brouard  3330:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3331:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3332:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3333:        /* 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)); */
                   3334:       }
                   3335:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3336:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3337:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3338:        /* 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]); */
                   3339:       }
                   3340:       for (k=1; k<=cptcovage;k++){
                   3341:        if(Dummy[Tvar[Tage[k]]]){
                   3342:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3343:        } else{
                   3344:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3345:        }
                   3346:        /* 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]); */
                   3347:       }
                   3348:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3349:        /* 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]); */
                   3350:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3351:       }
                   3352:       /* for (k=1; k<=cptcovn;k++)  */
                   3353:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3354:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3355:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3356:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3357:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3358:       
                   3359:       
1.126     brouard  3360:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3361:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3362:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3363:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3364:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3365:       /* if((int)age == 70){ */
                   3366:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3367:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3368:       /*         printf("%d pmmij ",i); */
                   3369:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3370:       /*           printf("%f ",pmmij[i][j]); */
                   3371:       /*         } */
                   3372:       /*         printf(" oldm "); */
                   3373:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3374:       /*           printf("%f ",oldm[i][j]); */
                   3375:       /*         } */
                   3376:       /*         printf("\n"); */
                   3377:       /*       } */
                   3378:       /* } */
1.126     brouard  3379:       savm=oldm;
                   3380:       oldm=newm;
                   3381:     }
                   3382:     for(i=1; i<=nlstate+ndeath; i++)
                   3383:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3384:        po[i][j][h]=newm[i][j];
                   3385:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3386:       }
1.128     brouard  3387:     /*printf("h=%d ",h);*/
1.126     brouard  3388:   } /* end h */
1.267     brouard  3389:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3390:   return po;
                   3391: }
                   3392: 
1.217     brouard  3393: /************* Higher Back Matrix Product ***************/
1.218     brouard  3394: /* 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  3395: 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  3396: {
1.266     brouard  3397:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3398:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3399:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3400:      nhstepm*hstepm matrices.
                   3401:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3402:      (typically every 2 years instead of every month which is too big
1.217     brouard  3403:      for the memory).
1.218     brouard  3404:      Model is determined by parameters x and covariates have to be
1.266     brouard  3405:      included manually here. Then we use a call to bmij(x and cov)
                   3406:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3407:   */
1.217     brouard  3408: 
                   3409:   int i, j, d, h, k;
1.266     brouard  3410:   double **out, cov[NCOVMAX+1], **bmij();
                   3411:   double **newm, ***newmm;
1.217     brouard  3412:   double agexact;
                   3413:   double agebegin, ageend;
1.222     brouard  3414:   double **oldm, **savm;
1.217     brouard  3415: 
1.266     brouard  3416:   newmm=po; /* To be saved */
                   3417:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3418:   /* Hstepm could be zero and should return the unit matrix */
                   3419:   for (i=1;i<=nlstate+ndeath;i++)
                   3420:     for (j=1;j<=nlstate+ndeath;j++){
                   3421:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3422:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3423:     }
                   3424:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3425:   for(h=1; h <=nhstepm; h++){
                   3426:     for(d=1; d <=hstepm; d++){
                   3427:       newm=savm;
                   3428:       /* Covariates have to be included here again */
                   3429:       cov[1]=1.;
1.271     brouard  3430:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3431:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3432:       cov[2]=agexact;
                   3433:       if(nagesqr==1)
1.222     brouard  3434:        cov[3]= agexact*agexact;
1.266     brouard  3435:       for (k=1; k<=cptcovn;k++){
                   3436:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3437:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3438:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3439:         /* 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)); */
                   3440:       }
1.267     brouard  3441:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3442:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3443:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3444:        /* 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]); */
                   3445:       }
                   3446:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3447:        if(Dummy[Tvar[Tage[k]]]){
                   3448:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3449:        } else{
                   3450:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3451:        }
                   3452:        /* 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]); */
                   3453:       }
                   3454:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3455:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3456:       }                        
1.217     brouard  3457:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3458:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3459: 
1.218     brouard  3460:       /* Careful transposed matrix */
1.266     brouard  3461:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3462:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3463:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3464:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3465:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3466:       /* if((int)age == 70){ */
                   3467:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3468:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3469:       /*         printf("%d pmmij ",i); */
                   3470:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3471:       /*           printf("%f ",pmmij[i][j]); */
                   3472:       /*         } */
                   3473:       /*         printf(" oldm "); */
                   3474:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3475:       /*           printf("%f ",oldm[i][j]); */
                   3476:       /*         } */
                   3477:       /*         printf("\n"); */
                   3478:       /*       } */
                   3479:       /* } */
                   3480:       savm=oldm;
                   3481:       oldm=newm;
                   3482:     }
                   3483:     for(i=1; i<=nlstate+ndeath; i++)
                   3484:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3485:        po[i][j][h]=newm[i][j];
1.268     brouard  3486:        /* if(h==nhstepm) */
                   3487:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3488:       }
1.268     brouard  3489:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3490:   } /* end h */
1.268     brouard  3491:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3492:   return po;
                   3493: }
                   3494: 
                   3495: 
1.162     brouard  3496: #ifdef NLOPT
                   3497:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3498:   double fret;
                   3499:   double *xt;
                   3500:   int j;
                   3501:   myfunc_data *d2 = (myfunc_data *) pd;
                   3502: /* xt = (p1-1); */
                   3503:   xt=vector(1,n); 
                   3504:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3505: 
                   3506:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3507:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3508:   printf("Function = %.12lf ",fret);
                   3509:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3510:   printf("\n");
                   3511:  free_vector(xt,1,n);
                   3512:   return fret;
                   3513: }
                   3514: #endif
1.126     brouard  3515: 
                   3516: /*************** log-likelihood *************/
                   3517: double func( double *x)
                   3518: {
1.226     brouard  3519:   int i, ii, j, k, mi, d, kk;
                   3520:   int ioffset=0;
                   3521:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3522:   double **out;
                   3523:   double lli; /* Individual log likelihood */
                   3524:   int s1, s2;
1.228     brouard  3525:   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  3526:   double bbh, survp;
                   3527:   long ipmx;
                   3528:   double agexact;
                   3529:   /*extern weight */
                   3530:   /* We are differentiating ll according to initial status */
                   3531:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3532:   /*for(i=1;i<imx;i++) 
                   3533:     printf(" %d\n",s[4][i]);
                   3534:   */
1.162     brouard  3535: 
1.226     brouard  3536:   ++countcallfunc;
1.162     brouard  3537: 
1.226     brouard  3538:   cov[1]=1.;
1.126     brouard  3539: 
1.226     brouard  3540:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3541:   ioffset=0;
1.226     brouard  3542:   if(mle==1){
                   3543:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3544:       /* Computes the values of the ncovmodel covariates of the model
                   3545:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3546:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3547:         to be observed in j being in i according to the model.
                   3548:       */
1.243     brouard  3549:       ioffset=2+nagesqr ;
1.233     brouard  3550:    /* Fixed */
1.234     brouard  3551:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3552:        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)*/
                   3553:       }
1.226     brouard  3554:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3555:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3556:         has been calculated etc */
                   3557:       /* For an individual i, wav[i] gives the number of effective waves */
                   3558:       /* We compute the contribution to Likelihood of each effective transition
                   3559:         mw[mi][i] is real wave of the mi th effectve wave */
                   3560:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3561:         s2=s[mw[mi+1][i]][i];
                   3562:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3563:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3564:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3565:       */
                   3566:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3567:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3568:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3569:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3570:        }
                   3571:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3572:          for (j=1;j<=nlstate+ndeath;j++){
                   3573:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3574:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3575:          }
                   3576:        for(d=0; d<dh[mi][i]; d++){
                   3577:          newm=savm;
                   3578:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3579:          cov[2]=agexact;
                   3580:          if(nagesqr==1)
                   3581:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3582:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3583:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3584:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3585:          else
                   3586:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3587:          }
                   3588:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3589:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3590:          savm=oldm;
                   3591:          oldm=newm;
                   3592:        } /* end mult */
                   3593:        
                   3594:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3595:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3596:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3597:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3598:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3599:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3600:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3601:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3602:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3603:                                 * -stepm/2 to stepm/2 .
                   3604:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3605:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3606:                                 */
1.234     brouard  3607:        s1=s[mw[mi][i]][i];
                   3608:        s2=s[mw[mi+1][i]][i];
                   3609:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3610:        /* bias bh is positive if real duration
                   3611:         * is higher than the multiple of stepm and negative otherwise.
                   3612:         */
                   3613:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3614:        if( s2 > nlstate){ 
                   3615:          /* i.e. if s2 is a death state and if the date of death is known 
                   3616:             then the contribution to the likelihood is the probability to 
                   3617:             die between last step unit time and current  step unit time, 
                   3618:             which is also equal to probability to die before dh 
                   3619:             minus probability to die before dh-stepm . 
                   3620:             In version up to 0.92 likelihood was computed
                   3621:             as if date of death was unknown. Death was treated as any other
                   3622:             health state: the date of the interview describes the actual state
                   3623:             and not the date of a change in health state. The former idea was
                   3624:             to consider that at each interview the state was recorded
                   3625:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3626:             introduced the exact date of death then we should have modified
                   3627:             the contribution of an exact death to the likelihood. This new
                   3628:             contribution is smaller and very dependent of the step unit
                   3629:             stepm. It is no more the probability to die between last interview
                   3630:             and month of death but the probability to survive from last
                   3631:             interview up to one month before death multiplied by the
                   3632:             probability to die within a month. Thanks to Chris
                   3633:             Jackson for correcting this bug.  Former versions increased
                   3634:             mortality artificially. The bad side is that we add another loop
                   3635:             which slows down the processing. The difference can be up to 10%
                   3636:             lower mortality.
                   3637:          */
                   3638:          /* If, at the beginning of the maximization mostly, the
                   3639:             cumulative probability or probability to be dead is
                   3640:             constant (ie = 1) over time d, the difference is equal to
                   3641:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3642:             s1 at precedent wave, to be dead a month before current
                   3643:             wave is equal to probability, being at state s1 at
                   3644:             precedent wave, to be dead at mont of the current
                   3645:             wave. Then the observed probability (that this person died)
                   3646:             is null according to current estimated parameter. In fact,
                   3647:             it should be very low but not zero otherwise the log go to
                   3648:             infinity.
                   3649:          */
1.183     brouard  3650: /* #ifdef INFINITYORIGINAL */
                   3651: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3652: /* #else */
                   3653: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3654: /*         lli=log(mytinydouble); */
                   3655: /*       else */
                   3656: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3657: /* #endif */
1.226     brouard  3658:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3659:          
1.226     brouard  3660:        } else if  ( s2==-1 ) { /* alive */
                   3661:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3662:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3663:          /*survp += out[s1][j]; */
                   3664:          lli= log(survp);
                   3665:        }
                   3666:        else if  (s2==-4) { 
                   3667:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3668:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3669:          lli= log(survp); 
                   3670:        } 
                   3671:        else if  (s2==-5) { 
                   3672:          for (j=1,survp=0. ; j<=2; j++)  
                   3673:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3674:          lli= log(survp); 
                   3675:        } 
                   3676:        else{
                   3677:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3678:          /*  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 */
                   3679:        } 
                   3680:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3681:        /*if(lli ==000.0)*/
                   3682:        /*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); */
                   3683:        ipmx +=1;
                   3684:        sw += weight[i];
                   3685:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3686:        /* if (lli < log(mytinydouble)){ */
                   3687:        /*   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); */
                   3688:        /*   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]); */
                   3689:        /* } */
                   3690:       } /* end of wave */
                   3691:     } /* end of individual */
                   3692:   }  else if(mle==2){
                   3693:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3694:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3695:       for(mi=1; mi<= wav[i]-1; mi++){
                   3696:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3697:          for (j=1;j<=nlstate+ndeath;j++){
                   3698:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3699:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3700:          }
                   3701:        for(d=0; d<=dh[mi][i]; d++){
                   3702:          newm=savm;
                   3703:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3704:          cov[2]=agexact;
                   3705:          if(nagesqr==1)
                   3706:            cov[3]= agexact*agexact;
                   3707:          for (kk=1; kk<=cptcovage;kk++) {
                   3708:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3709:          }
                   3710:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3711:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3712:          savm=oldm;
                   3713:          oldm=newm;
                   3714:        } /* end mult */
                   3715:       
                   3716:        s1=s[mw[mi][i]][i];
                   3717:        s2=s[mw[mi+1][i]][i];
                   3718:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3719:        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 */
                   3720:        ipmx +=1;
                   3721:        sw += weight[i];
                   3722:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3723:       } /* end of wave */
                   3724:     } /* end of individual */
                   3725:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3726:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3727:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3728:       for(mi=1; mi<= wav[i]-1; mi++){
                   3729:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3730:          for (j=1;j<=nlstate+ndeath;j++){
                   3731:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3732:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3733:          }
                   3734:        for(d=0; d<dh[mi][i]; d++){
                   3735:          newm=savm;
                   3736:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3737:          cov[2]=agexact;
                   3738:          if(nagesqr==1)
                   3739:            cov[3]= agexact*agexact;
                   3740:          for (kk=1; kk<=cptcovage;kk++) {
                   3741:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3742:          }
                   3743:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3744:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3745:          savm=oldm;
                   3746:          oldm=newm;
                   3747:        } /* end mult */
                   3748:       
                   3749:        s1=s[mw[mi][i]][i];
                   3750:        s2=s[mw[mi+1][i]][i];
                   3751:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3752:        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 */
                   3753:        ipmx +=1;
                   3754:        sw += weight[i];
                   3755:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3756:       } /* end of wave */
                   3757:     } /* end of individual */
                   3758:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3759:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3760:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3761:       for(mi=1; mi<= wav[i]-1; mi++){
                   3762:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3763:          for (j=1;j<=nlstate+ndeath;j++){
                   3764:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3765:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3766:          }
                   3767:        for(d=0; d<dh[mi][i]; d++){
                   3768:          newm=savm;
                   3769:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3770:          cov[2]=agexact;
                   3771:          if(nagesqr==1)
                   3772:            cov[3]= agexact*agexact;
                   3773:          for (kk=1; kk<=cptcovage;kk++) {
                   3774:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3775:          }
1.126     brouard  3776:        
1.226     brouard  3777:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3778:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3779:          savm=oldm;
                   3780:          oldm=newm;
                   3781:        } /* end mult */
                   3782:       
                   3783:        s1=s[mw[mi][i]][i];
                   3784:        s2=s[mw[mi+1][i]][i];
                   3785:        if( s2 > nlstate){ 
                   3786:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3787:        } else if  ( s2==-1 ) { /* alive */
                   3788:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3789:            survp += out[s1][j];
                   3790:          lli= log(survp);
                   3791:        }else{
                   3792:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3793:        }
                   3794:        ipmx +=1;
                   3795:        sw += weight[i];
                   3796:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3797: /*     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  3798:       } /* end of wave */
                   3799:     } /* end of individual */
                   3800:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3801:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3802:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3803:       for(mi=1; mi<= wav[i]-1; mi++){
                   3804:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3805:          for (j=1;j<=nlstate+ndeath;j++){
                   3806:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3807:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3808:          }
                   3809:        for(d=0; d<dh[mi][i]; d++){
                   3810:          newm=savm;
                   3811:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3812:          cov[2]=agexact;
                   3813:          if(nagesqr==1)
                   3814:            cov[3]= agexact*agexact;
                   3815:          for (kk=1; kk<=cptcovage;kk++) {
                   3816:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3817:          }
1.126     brouard  3818:        
1.226     brouard  3819:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3820:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3821:          savm=oldm;
                   3822:          oldm=newm;
                   3823:        } /* end mult */
                   3824:       
                   3825:        s1=s[mw[mi][i]][i];
                   3826:        s2=s[mw[mi+1][i]][i];
                   3827:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3828:        ipmx +=1;
                   3829:        sw += weight[i];
                   3830:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3831:        /*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]);*/
                   3832:       } /* end of wave */
                   3833:     } /* end of individual */
                   3834:   } /* End of if */
                   3835:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3836:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3837:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3838:   return -l;
1.126     brouard  3839: }
                   3840: 
                   3841: /*************** log-likelihood *************/
                   3842: double funcone( double *x)
                   3843: {
1.228     brouard  3844:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3845:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3846:   int ioffset=0;
1.131     brouard  3847:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3848:   double **out;
                   3849:   double lli; /* Individual log likelihood */
                   3850:   double llt;
                   3851:   int s1, s2;
1.228     brouard  3852:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3853: 
1.126     brouard  3854:   double bbh, survp;
1.187     brouard  3855:   double agexact;
1.214     brouard  3856:   double agebegin, ageend;
1.126     brouard  3857:   /*extern weight */
                   3858:   /* We are differentiating ll according to initial status */
                   3859:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3860:   /*for(i=1;i<imx;i++) 
                   3861:     printf(" %d\n",s[4][i]);
                   3862:   */
                   3863:   cov[1]=1.;
                   3864: 
                   3865:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3866:   ioffset=0;
                   3867:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3868:     /* ioffset=2+nagesqr+cptcovage; */
                   3869:     ioffset=2+nagesqr;
1.232     brouard  3870:     /* Fixed */
1.224     brouard  3871:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3872:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  3873:     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  3874:       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)*/
                   3875: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3876: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3877: /*    cov[2+6]=covar[2][i]; V2  */
                   3878: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3879: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3880: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3881: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3882: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3883: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3884:     }
1.232     brouard  3885:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3886:     /*   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?)*\/ */
                   3887:     /* } */
1.231     brouard  3888:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3889:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3890:     /* } */
1.225     brouard  3891:     
1.233     brouard  3892: 
                   3893:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3894:     /* Wave varying (but not age varying) */
                   3895:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3896:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3897:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3898:       }
1.232     brouard  3899:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3900:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3901:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3902:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3903:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3904:       /* 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  3905:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3906:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3907:       /*       /\* 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]); *\/ */
                   3908:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3909:       /* } */
1.126     brouard  3910:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  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:        }
1.214     brouard  3915:       
                   3916:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3917:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3918:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3919:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3920:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3921:          and mw[mi+1][i]. dh depends on stepm.*/
                   3922:        newm=savm;
1.247     brouard  3923:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3924:        cov[2]=agexact;
                   3925:        if(nagesqr==1)
                   3926:          cov[3]= agexact*agexact;
                   3927:        for (kk=1; kk<=cptcovage;kk++) {
                   3928:          if(!FixedV[Tvar[Tage[kk]]])
                   3929:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3930:          else
                   3931:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3932:        }
                   3933:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3934:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3935:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3936:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3937:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3938:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3939:        savm=oldm;
                   3940:        oldm=newm;
1.126     brouard  3941:       } /* end mult */
                   3942:       
                   3943:       s1=s[mw[mi][i]][i];
                   3944:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3945:       /* if(s2==-1){ */
1.268     brouard  3946:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3947:       /*       /\* exit(1); *\/ */
                   3948:       /* } */
1.126     brouard  3949:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3950:       /* bias is positive if real duration
                   3951:        * is higher than the multiple of stepm and negative otherwise.
                   3952:        */
                   3953:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3954:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3955:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3956:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3957:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3958:        lli= log(survp);
1.126     brouard  3959:       }else if (mle==1){
1.242     brouard  3960:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3961:       } else if(mle==2){
1.242     brouard  3962:        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  3963:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3964:        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  3965:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3966:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3967:       } else{  /* mle=0 back to 1 */
1.242     brouard  3968:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3969:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3970:       } /* End of if */
                   3971:       ipmx +=1;
                   3972:       sw += weight[i];
                   3973:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3974:       /*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  3975:       if(globpr){
1.246     brouard  3976:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3977:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3978:                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  3979:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3980:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3981:          llt +=ll[k]*gipmx/gsw;
                   3982:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3983:        }
                   3984:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3985:       }
1.232     brouard  3986:        } /* end of wave */
                   3987: } /* end of individual */
                   3988: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3989: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3990: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3991: if(globpr==0){ /* First time we count the contributions and weights */
                   3992:        gipmx=ipmx;
                   3993:        gsw=sw;
                   3994: }
                   3995: return -l;
1.126     brouard  3996: }
                   3997: 
                   3998: 
                   3999: /*************** function likelione ***********/
1.292     brouard  4000: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4001: {
                   4002:   /* This routine should help understanding what is done with 
                   4003:      the selection of individuals/waves and
                   4004:      to check the exact contribution to the likelihood.
                   4005:      Plotting could be done.
                   4006:    */
                   4007:   int k;
                   4008: 
                   4009:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4010:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4011:     strcat(fileresilk,fileresu);
1.126     brouard  4012:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4013:       printf("Problem with resultfile: %s\n", fileresilk);
                   4014:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4015:     }
1.214     brouard  4016:     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");
                   4017:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4018:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4019:     for(k=1; k<=nlstate; k++) 
                   4020:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4021:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4022:   }
                   4023: 
1.292     brouard  4024:   *fretone=(*func)(p);
1.126     brouard  4025:   if(*globpri !=0){
                   4026:     fclose(ficresilk);
1.205     brouard  4027:     if (mle ==0)
                   4028:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4029:     else if(mle >=1)
                   4030:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4031:     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  4032:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4033:       
                   4034:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4035:       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  4036: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4037:     }
1.207     brouard  4038:     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  4039: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4040:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4041: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4042:     fflush(fichtm);
1.205     brouard  4043:   }
1.126     brouard  4044:   return;
                   4045: }
                   4046: 
                   4047: 
                   4048: /*********** Maximum Likelihood Estimation ***************/
                   4049: 
                   4050: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4051: {
1.165     brouard  4052:   int i,j, iter=0;
1.126     brouard  4053:   double **xi;
                   4054:   double fret;
                   4055:   double fretone; /* Only one call to likelihood */
                   4056:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4057: 
                   4058: #ifdef NLOPT
                   4059:   int creturn;
                   4060:   nlopt_opt opt;
                   4061:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4062:   double *lb;
                   4063:   double minf; /* the minimum objective value, upon return */
                   4064:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4065:   myfunc_data dinst, *d = &dinst;
                   4066: #endif
                   4067: 
                   4068: 
1.126     brouard  4069:   xi=matrix(1,npar,1,npar);
                   4070:   for (i=1;i<=npar;i++)
                   4071:     for (j=1;j<=npar;j++)
                   4072:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4073:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4074:   strcpy(filerespow,"POW_"); 
1.126     brouard  4075:   strcat(filerespow,fileres);
                   4076:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4077:     printf("Problem with resultfile: %s\n", filerespow);
                   4078:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4079:   }
                   4080:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4081:   for (i=1;i<=nlstate;i++)
                   4082:     for(j=1;j<=nlstate+ndeath;j++)
                   4083:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4084:   fprintf(ficrespow,"\n");
1.162     brouard  4085: #ifdef POWELL
1.126     brouard  4086:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4087: #endif
1.126     brouard  4088: 
1.162     brouard  4089: #ifdef NLOPT
                   4090: #ifdef NEWUOA
                   4091:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4092: #else
                   4093:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4094: #endif
                   4095:   lb=vector(0,npar-1);
                   4096:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4097:   nlopt_set_lower_bounds(opt, lb);
                   4098:   nlopt_set_initial_step1(opt, 0.1);
                   4099:   
                   4100:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4101:   d->function = func;
                   4102:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4103:   nlopt_set_min_objective(opt, myfunc, d);
                   4104:   nlopt_set_xtol_rel(opt, ftol);
                   4105:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4106:     printf("nlopt failed! %d\n",creturn); 
                   4107:   }
                   4108:   else {
                   4109:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4110:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4111:     iter=1; /* not equal */
                   4112:   }
                   4113:   nlopt_destroy(opt);
                   4114: #endif
1.126     brouard  4115:   free_matrix(xi,1,npar,1,npar);
                   4116:   fclose(ficrespow);
1.203     brouard  4117:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4118:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4119:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4120: 
                   4121: }
                   4122: 
                   4123: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4124: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4125: {
                   4126:   double  **a,**y,*x,pd;
1.203     brouard  4127:   /* double **hess; */
1.164     brouard  4128:   int i, j;
1.126     brouard  4129:   int *indx;
                   4130: 
                   4131:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4132:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4133:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4134:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4135:   double gompertz(double p[]);
1.203     brouard  4136:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4137: 
                   4138:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4139:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4140:   for (i=1;i<=npar;i++){
1.203     brouard  4141:     printf("%d-",i);fflush(stdout);
                   4142:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4143:    
                   4144:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4145:     
                   4146:     /*  printf(" %f ",p[i]);
                   4147:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4148:   }
                   4149:   
                   4150:   for (i=1;i<=npar;i++) {
                   4151:     for (j=1;j<=npar;j++)  {
                   4152:       if (j>i) { 
1.203     brouard  4153:        printf(".%d-%d",i,j);fflush(stdout);
                   4154:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4155:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4156:        
                   4157:        hess[j][i]=hess[i][j];    
                   4158:        /*printf(" %lf ",hess[i][j]);*/
                   4159:       }
                   4160:     }
                   4161:   }
                   4162:   printf("\n");
                   4163:   fprintf(ficlog,"\n");
                   4164: 
                   4165:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4166:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4167:   
                   4168:   a=matrix(1,npar,1,npar);
                   4169:   y=matrix(1,npar,1,npar);
                   4170:   x=vector(1,npar);
                   4171:   indx=ivector(1,npar);
                   4172:   for (i=1;i<=npar;i++)
                   4173:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4174:   ludcmp(a,npar,indx,&pd);
                   4175: 
                   4176:   for (j=1;j<=npar;j++) {
                   4177:     for (i=1;i<=npar;i++) x[i]=0;
                   4178:     x[j]=1;
                   4179:     lubksb(a,npar,indx,x);
                   4180:     for (i=1;i<=npar;i++){ 
                   4181:       matcov[i][j]=x[i];
                   4182:     }
                   4183:   }
                   4184: 
                   4185:   printf("\n#Hessian matrix#\n");
                   4186:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4187:   for (i=1;i<=npar;i++) { 
                   4188:     for (j=1;j<=npar;j++) { 
1.203     brouard  4189:       printf("%.6e ",hess[i][j]);
                   4190:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4191:     }
                   4192:     printf("\n");
                   4193:     fprintf(ficlog,"\n");
                   4194:   }
                   4195: 
1.203     brouard  4196:   /* printf("\n#Covariance matrix#\n"); */
                   4197:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4198:   /* for (i=1;i<=npar;i++) {  */
                   4199:   /*   for (j=1;j<=npar;j++) {  */
                   4200:   /*     printf("%.6e ",matcov[i][j]); */
                   4201:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4202:   /*   } */
                   4203:   /*   printf("\n"); */
                   4204:   /*   fprintf(ficlog,"\n"); */
                   4205:   /* } */
                   4206: 
1.126     brouard  4207:   /* Recompute Inverse */
1.203     brouard  4208:   /* for (i=1;i<=npar;i++) */
                   4209:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4210:   /* ludcmp(a,npar,indx,&pd); */
                   4211: 
                   4212:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4213: 
                   4214:   /* for (j=1;j<=npar;j++) { */
                   4215:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4216:   /*   x[j]=1; */
                   4217:   /*   lubksb(a,npar,indx,x); */
                   4218:   /*   for (i=1;i<=npar;i++){  */
                   4219:   /*     y[i][j]=x[i]; */
                   4220:   /*     printf("%.3e ",y[i][j]); */
                   4221:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4222:   /*   } */
                   4223:   /*   printf("\n"); */
                   4224:   /*   fprintf(ficlog,"\n"); */
                   4225:   /* } */
                   4226: 
                   4227:   /* Verifying the inverse matrix */
                   4228: #ifdef DEBUGHESS
                   4229:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4230: 
1.203     brouard  4231:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4232:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4233: 
                   4234:   for (j=1;j<=npar;j++) {
                   4235:     for (i=1;i<=npar;i++){ 
1.203     brouard  4236:       printf("%.2f ",y[i][j]);
                   4237:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4238:     }
                   4239:     printf("\n");
                   4240:     fprintf(ficlog,"\n");
                   4241:   }
1.203     brouard  4242: #endif
1.126     brouard  4243: 
                   4244:   free_matrix(a,1,npar,1,npar);
                   4245:   free_matrix(y,1,npar,1,npar);
                   4246:   free_vector(x,1,npar);
                   4247:   free_ivector(indx,1,npar);
1.203     brouard  4248:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4249: 
                   4250: 
                   4251: }
                   4252: 
                   4253: /*************** hessian matrix ****************/
                   4254: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4255: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4256:   int i;
                   4257:   int l=1, lmax=20;
1.203     brouard  4258:   double k1,k2, res, fx;
1.132     brouard  4259:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4260:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4261:   int k=0,kmax=10;
                   4262:   double l1;
                   4263: 
                   4264:   fx=func(x);
                   4265:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4266:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4267:     l1=pow(10,l);
                   4268:     delts=delt;
                   4269:     for(k=1 ; k <kmax; k=k+1){
                   4270:       delt = delta*(l1*k);
                   4271:       p2[theta]=x[theta] +delt;
1.145     brouard  4272:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4273:       p2[theta]=x[theta]-delt;
                   4274:       k2=func(p2)-fx;
                   4275:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4276:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4277:       
1.203     brouard  4278: #ifdef DEBUGHESSII
1.126     brouard  4279:       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);
                   4280:       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);
                   4281: #endif
                   4282:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4283:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4284:        k=kmax;
                   4285:       }
                   4286:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4287:        k=kmax; l=lmax*10;
1.126     brouard  4288:       }
                   4289:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4290:        delts=delt;
                   4291:       }
1.203     brouard  4292:     } /* End loop k */
1.126     brouard  4293:   }
                   4294:   delti[theta]=delts;
                   4295:   return res; 
                   4296:   
                   4297: }
                   4298: 
1.203     brouard  4299: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4300: {
                   4301:   int i;
1.164     brouard  4302:   int l=1, lmax=20;
1.126     brouard  4303:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4304:   double p2[MAXPARM+1];
1.203     brouard  4305:   int k, kmax=1;
                   4306:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4307: 
                   4308:   int firstime=0;
1.203     brouard  4309:   
1.126     brouard  4310:   fx=func(x);
1.203     brouard  4311:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4312:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4313:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4314:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4315:     k1=func(p2)-fx;
                   4316:   
1.203     brouard  4317:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4318:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4319:     k2=func(p2)-fx;
                   4320:   
1.203     brouard  4321:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4322:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4323:     k3=func(p2)-fx;
                   4324:   
1.203     brouard  4325:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4326:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4327:     k4=func(p2)-fx;
1.203     brouard  4328:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4329:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4330:       firstime=1;
1.203     brouard  4331:       kmax=kmax+10;
1.208     brouard  4332:     }
                   4333:     if(kmax >=10 || firstime ==1){
1.246     brouard  4334:       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);
                   4335:       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  4336:       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);
                   4337:       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);
                   4338:     }
                   4339: #ifdef DEBUGHESSIJ
                   4340:     v1=hess[thetai][thetai];
                   4341:     v2=hess[thetaj][thetaj];
                   4342:     cv12=res;
                   4343:     /* Computing eigen value of Hessian matrix */
                   4344:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4345:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4346:     if ((lc2 <0) || (lc1 <0) ){
                   4347:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4348:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4349:       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);
                   4350:       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);
                   4351:     }
1.126     brouard  4352: #endif
                   4353:   }
                   4354:   return res;
                   4355: }
                   4356: 
1.203     brouard  4357:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4358: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4359: /* { */
                   4360: /*   int i; */
                   4361: /*   int l=1, lmax=20; */
                   4362: /*   double k1,k2,k3,k4,res,fx; */
                   4363: /*   double p2[MAXPARM+1]; */
                   4364: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4365: /*   int k=0,kmax=10; */
                   4366: /*   double l1; */
                   4367:   
                   4368: /*   fx=func(x); */
                   4369: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4370: /*     l1=pow(10,l); */
                   4371: /*     delts=delt; */
                   4372: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4373: /*       delt = delti*(l1*k); */
                   4374: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4375: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4376: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4377: /*       k1=func(p2)-fx; */
                   4378:       
                   4379: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4380: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4381: /*       k2=func(p2)-fx; */
                   4382:       
                   4383: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4384: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4385: /*       k3=func(p2)-fx; */
                   4386:       
                   4387: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4388: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4389: /*       k4=func(p2)-fx; */
                   4390: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4391: /* #ifdef DEBUGHESSIJ */
                   4392: /*       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); */
                   4393: /*       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); */
                   4394: /* #endif */
                   4395: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4396: /*     k=kmax; */
                   4397: /*       } */
                   4398: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4399: /*     k=kmax; l=lmax*10; */
                   4400: /*       } */
                   4401: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4402: /*     delts=delt; */
                   4403: /*       } */
                   4404: /*     } /\* End loop k *\/ */
                   4405: /*   } */
                   4406: /*   delti[theta]=delts; */
                   4407: /*   return res;  */
                   4408: /* } */
                   4409: 
                   4410: 
1.126     brouard  4411: /************** Inverse of matrix **************/
                   4412: void ludcmp(double **a, int n, int *indx, double *d) 
                   4413: { 
                   4414:   int i,imax,j,k; 
                   4415:   double big,dum,sum,temp; 
                   4416:   double *vv; 
                   4417:  
                   4418:   vv=vector(1,n); 
                   4419:   *d=1.0; 
                   4420:   for (i=1;i<=n;i++) { 
                   4421:     big=0.0; 
                   4422:     for (j=1;j<=n;j++) 
                   4423:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4424:     if (big == 0.0){
                   4425:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4426:       for (j=1;j<=n;j++) {
                   4427:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4428:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4429:       }
                   4430:       fflush(ficlog);
                   4431:       fclose(ficlog);
                   4432:       nrerror("Singular matrix in routine ludcmp"); 
                   4433:     }
1.126     brouard  4434:     vv[i]=1.0/big; 
                   4435:   } 
                   4436:   for (j=1;j<=n;j++) { 
                   4437:     for (i=1;i<j;i++) { 
                   4438:       sum=a[i][j]; 
                   4439:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4440:       a[i][j]=sum; 
                   4441:     } 
                   4442:     big=0.0; 
                   4443:     for (i=j;i<=n;i++) { 
                   4444:       sum=a[i][j]; 
                   4445:       for (k=1;k<j;k++) 
                   4446:        sum -= a[i][k]*a[k][j]; 
                   4447:       a[i][j]=sum; 
                   4448:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4449:        big=dum; 
                   4450:        imax=i; 
                   4451:       } 
                   4452:     } 
                   4453:     if (j != imax) { 
                   4454:       for (k=1;k<=n;k++) { 
                   4455:        dum=a[imax][k]; 
                   4456:        a[imax][k]=a[j][k]; 
                   4457:        a[j][k]=dum; 
                   4458:       } 
                   4459:       *d = -(*d); 
                   4460:       vv[imax]=vv[j]; 
                   4461:     } 
                   4462:     indx[j]=imax; 
                   4463:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4464:     if (j != n) { 
                   4465:       dum=1.0/(a[j][j]); 
                   4466:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4467:     } 
                   4468:   } 
                   4469:   free_vector(vv,1,n);  /* Doesn't work */
                   4470: ;
                   4471: } 
                   4472: 
                   4473: void lubksb(double **a, int n, int *indx, double b[]) 
                   4474: { 
                   4475:   int i,ii=0,ip,j; 
                   4476:   double sum; 
                   4477:  
                   4478:   for (i=1;i<=n;i++) { 
                   4479:     ip=indx[i]; 
                   4480:     sum=b[ip]; 
                   4481:     b[ip]=b[i]; 
                   4482:     if (ii) 
                   4483:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4484:     else if (sum) ii=i; 
                   4485:     b[i]=sum; 
                   4486:   } 
                   4487:   for (i=n;i>=1;i--) { 
                   4488:     sum=b[i]; 
                   4489:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4490:     b[i]=sum/a[i][i]; 
                   4491:   } 
                   4492: } 
                   4493: 
                   4494: void pstamp(FILE *fichier)
                   4495: {
1.196     brouard  4496:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4497: }
                   4498: 
1.297     brouard  4499: void date2dmy(double date,double *day, double *month, double *year){
                   4500:   double yp=0., yp1=0., yp2=0.;
                   4501:   
                   4502:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4503:                        fractional in yp1 */
                   4504:   *year=yp;
                   4505:   yp2=modf((yp1*12),&yp);
                   4506:   *month=yp;
                   4507:   yp1=modf((yp2*30.5),&yp);
                   4508:   *day=yp;
                   4509:   if(*day==0) *day=1;
                   4510:   if(*month==0) *month=1;
                   4511: }
                   4512: 
1.253     brouard  4513: 
                   4514: 
1.126     brouard  4515: /************ Frequencies ********************/
1.251     brouard  4516: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4517:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4518:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4519: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4520:   
1.265     brouard  4521:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4522:   int iind=0, iage=0;
                   4523:   int mi; /* Effective wave */
                   4524:   int first;
                   4525:   double ***freq; /* Frequencies */
1.268     brouard  4526:   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 */
                   4527:   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  4528:   double *meanq, *stdq, *idq;
1.226     brouard  4529:   double **meanqt;
                   4530:   double *pp, **prop, *posprop, *pospropt;
                   4531:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4532:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4533:   double agebegin, ageend;
                   4534:     
                   4535:   pp=vector(1,nlstate);
1.251     brouard  4536:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4537:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4538:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4539:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4540:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4541:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4542:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4543:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4544:   strcpy(fileresp,"P_");
                   4545:   strcat(fileresp,fileresu);
                   4546:   /*strcat(fileresphtm,fileresu);*/
                   4547:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4548:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4549:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4550:     exit(0);
                   4551:   }
1.240     brouard  4552:   
1.226     brouard  4553:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4554:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4555:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4556:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4557:     fflush(ficlog);
                   4558:     exit(70); 
                   4559:   }
                   4560:   else{
                   4561:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4562: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4563: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4564:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4565:   }
1.237     brouard  4566:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
1.240     brouard  4567:   
1.226     brouard  4568:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4569:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4570:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4571:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4572:     fflush(ficlog);
                   4573:     exit(70); 
1.240     brouard  4574:   } else{
1.226     brouard  4575:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4576: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4577: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4578:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4579:   }
1.240     brouard  4580:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>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);
                   4581:   
1.253     brouard  4582:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4583:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4584:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4585:   j1=0;
1.126     brouard  4586:   
1.227     brouard  4587:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4588:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4589:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4590:   
                   4591:   
1.226     brouard  4592:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4593:      reference=low_education V1=0,V2=0
                   4594:      med_educ                V1=1 V2=0, 
                   4595:      high_educ               V1=0 V2=1
                   4596:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4597:   */
1.249     brouard  4598:   dateintsum=0;
                   4599:   k2cpt=0;
                   4600: 
1.253     brouard  4601:   if(cptcoveff == 0 )
1.265     brouard  4602:     nl=1;  /* Constant and age model only */
1.253     brouard  4603:   else
                   4604:     nl=2;
1.265     brouard  4605: 
                   4606:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4607:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4608:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4609:    *     freq[s1][s2][iage] =0.
                   4610:    *     Loop on iind
                   4611:    *       ++freq[s1][s2][iage] weighted
                   4612:    *     end iind
                   4613:    *     if covariate and j!0
                   4614:    *       headers Variable on one line
                   4615:    *     endif cov j!=0
                   4616:    *     header of frequency table by age
                   4617:    *     Loop on age
                   4618:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4619:    *       pos+=freq[s1][s2][iage] weighted
                   4620:    *       Loop on s1 initial state
                   4621:    *         fprintf(ficresp
                   4622:    *       end s1
                   4623:    *     end age
                   4624:    *     if j!=0 computes starting values
                   4625:    *     end compute starting values
                   4626:    *   end j1
                   4627:    * end nl 
                   4628:    */
1.253     brouard  4629:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4630:     if(nj==1)
                   4631:       j=0;  /* First pass for the constant */
1.265     brouard  4632:     else{
1.253     brouard  4633:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4634:     }
1.251     brouard  4635:     first=1;
1.265     brouard  4636:     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  4637:       posproptt=0.;
                   4638:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4639:        scanf("%d", i);*/
                   4640:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4641:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4642:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4643:            freq[i][s2][m]=0;
1.251     brouard  4644:       
                   4645:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4646:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4647:          prop[i][m]=0;
                   4648:        posprop[i]=0;
                   4649:        pospropt[i]=0;
                   4650:       }
1.283     brouard  4651:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4652:         idq[z1]=0.;
                   4653:         meanq[z1]=0.;
                   4654:         stdq[z1]=0.;
1.283     brouard  4655:       }
                   4656:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4657:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4658:       /*         meanqt[m][z1]=0.; */
                   4659:       /*       } */
                   4660:       /* }       */
1.251     brouard  4661:       /* dateintsum=0; */
                   4662:       /* k2cpt=0; */
                   4663:       
1.265     brouard  4664:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4665:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4666:        bool=1;
                   4667:        if(j !=0){
                   4668:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4669:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4670:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4671:                /* if(Tvaraff[z1] ==-20){ */
                   4672:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4673:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4674:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4675:                /* }else  */
                   4676:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4677:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4678:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4679:                  /* 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", 
                   4680:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4681:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4682:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4683:                } /* Onlyf fixed */
                   4684:              } /* end z1 */
                   4685:            } /* cptcovn > 0 */
                   4686:          } /* end any */
                   4687:        }/* end j==0 */
1.265     brouard  4688:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4689:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4690:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4691:            m=mw[mi][iind];
                   4692:            if(j!=0){
                   4693:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4694:                for (z1=1; z1<=cptcoveff; z1++) {
                   4695:                  if( Fixed[Tmodelind[z1]]==1){
                   4696:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4697:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4698:                                                                                      value is -1, we don't select. It differs from the 
                   4699:                                                                                      constant and age model which counts them. */
                   4700:                      bool=0; /* not selected */
                   4701:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4702:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4703:                      bool=0;
                   4704:                    }
                   4705:                  }
                   4706:                }
                   4707:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4708:            } /* end j==0 */
                   4709:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4710:            if(bool==1){ /*Selected */
1.251     brouard  4711:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4712:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4713:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4714:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4715:              if(m >=firstpass && m <=lastpass){
                   4716:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4717:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4718:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4719:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4720:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4721:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4722:                if (m<lastpass) {
                   4723:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4724:                  /*   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]); */
                   4725:                  if(s[m][iind]==-1)
                   4726:                    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.));
                   4727:                  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  4728:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   4729:                    if(!isnan(covar[ncovcol+z1][iind])){
                   4730:                        idq[z1]=idq[z1]+weight[iind];
                   4731:                        meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4732:                        /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   4733:                        stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4734:                    }
1.284     brouard  4735:                  }
1.251     brouard  4736:                  /* if((int)agev[m][iind] == 55) */
                   4737:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4738:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4739:                  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  4740:                }
1.251     brouard  4741:              } /* end if between passes */  
                   4742:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4743:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4744:                k2cpt++;
                   4745:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4746:              }
1.251     brouard  4747:            }else{
                   4748:              bool=1;
                   4749:            }/* end bool 2 */
                   4750:          } /* end m */
1.284     brouard  4751:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4752:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4753:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4754:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4755:          /* } */
1.251     brouard  4756:        } /* end bool */
                   4757:       } /* end iind = 1 to imx */
                   4758:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4759:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4760:       
                   4761:       
                   4762:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4763:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4764:         pstamp(ficresp);
1.251     brouard  4765:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4766:         pstamp(ficresp);
1.251     brouard  4767:        printf( "\n#********** Variable "); 
                   4768:        fprintf(ficresp, "\n#********** Variable "); 
                   4769:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4770:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4771:        fprintf(ficlog, "\n#********** Variable "); 
                   4772:        for (z1=1; z1<=cptcoveff; z1++){
                   4773:          if(!FixedV[Tvaraff[z1]]){
                   4774:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4775:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4776:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4777:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4778:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4779:          }else{
1.251     brouard  4780:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4781:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4782:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4783:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4784:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4785:          }
                   4786:        }
                   4787:        printf( "**********\n#");
                   4788:        fprintf(ficresp, "**********\n#");
                   4789:        fprintf(ficresphtm, "**********</h3>\n");
                   4790:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4791:        fprintf(ficlog, "**********\n");
                   4792:       }
1.284     brouard  4793:       /*
                   4794:        Printing means of quantitative variables if any
                   4795:       */
                   4796:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  4797:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  4798:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  4799:        if(weightopt==1){
                   4800:          printf(" Weighted mean and standard deviation of");
                   4801:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4802:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4803:        }
1.311     brouard  4804:        /* mu = \frac{w x}{\sum w}
                   4805:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   4806:        */
                   4807:        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]));
                   4808:        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]));
                   4809:        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  4810:       }
                   4811:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4812:       /*       for(m=1;m<=lastpass;m++){ */
                   4813:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4814:       /*   } */
                   4815:       /* } */
1.283     brouard  4816: 
1.251     brouard  4817:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4818:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4819:         fprintf(ficresp, " Age");
                   4820:       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  4821:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4822:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4823:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4824:       }
1.265     brouard  4825:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4826:       fprintf(ficresphtm, "\n");
                   4827:       
                   4828:       /* Header of frequency table by age */
                   4829:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4830:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4831:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4832:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4833:          if(s2!=0 && m!=0)
                   4834:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4835:        }
1.226     brouard  4836:       }
1.251     brouard  4837:       fprintf(ficresphtmfr, "\n");
                   4838:     
                   4839:       /* For each age */
                   4840:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4841:        fprintf(ficresphtm,"<tr>");
                   4842:        if(iage==iagemax+1){
                   4843:          fprintf(ficlog,"1");
                   4844:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4845:        }else if(iage==iagemax+2){
                   4846:          fprintf(ficlog,"0");
                   4847:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4848:        }else if(iage==iagemax+3){
                   4849:          fprintf(ficlog,"Total");
                   4850:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4851:        }else{
1.240     brouard  4852:          if(first==1){
1.251     brouard  4853:            first=0;
                   4854:            printf("See log file for details...\n");
                   4855:          }
                   4856:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4857:          fprintf(ficlog,"Age %d", iage);
                   4858:        }
1.265     brouard  4859:        for(s1=1; s1 <=nlstate ; s1++){
                   4860:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4861:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4862:        }
1.265     brouard  4863:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4864:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4865:            pos += freq[s1][m][iage];
                   4866:          if(pp[s1]>=1.e-10){
1.251     brouard  4867:            if(first==1){
1.265     brouard  4868:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4869:            }
1.265     brouard  4870:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4871:          }else{
                   4872:            if(first==1)
1.265     brouard  4873:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4874:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4875:          }
                   4876:        }
                   4877:       
1.265     brouard  4878:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4879:          /* posprop[s1]=0; */
                   4880:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4881:            pp[s1] += freq[s1][m][iage];
                   4882:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4883:       
                   4884:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4885:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4886:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4887:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4888:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4889:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4890:        }
                   4891:        
                   4892:        /* Writing ficresp */
                   4893:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4894:           if( iage <= iagemax){
                   4895:            fprintf(ficresp," %d",iage);
                   4896:           }
                   4897:         }else if( nj==2){
                   4898:           if( iage <= iagemax){
                   4899:            fprintf(ficresp," %d",iage);
                   4900:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4901:           }
1.240     brouard  4902:        }
1.265     brouard  4903:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4904:          if(pos>=1.e-5){
1.251     brouard  4905:            if(first==1)
1.265     brouard  4906:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4907:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4908:          }else{
                   4909:            if(first==1)
1.265     brouard  4910:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4911:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4912:          }
                   4913:          if( iage <= iagemax){
                   4914:            if(pos>=1.e-5){
1.265     brouard  4915:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4916:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4917:               }else if( nj==2){
                   4918:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4919:               }
                   4920:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4921:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4922:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4923:            } else{
                   4924:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4925:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4926:            }
1.240     brouard  4927:          }
1.265     brouard  4928:          pospropt[s1] +=posprop[s1];
                   4929:        } /* end loop s1 */
1.251     brouard  4930:        /* pospropt=0.; */
1.265     brouard  4931:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4932:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4933:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4934:              if(first==1){
1.265     brouard  4935:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4936:              }
1.265     brouard  4937:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4938:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4939:            }
1.265     brouard  4940:            if(s1!=0 && m!=0)
                   4941:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4942:          }
1.265     brouard  4943:        } /* end loop s1 */
1.251     brouard  4944:        posproptt=0.; 
1.265     brouard  4945:        for(s1=1; s1 <=nlstate; s1++){
                   4946:          posproptt += pospropt[s1];
1.251     brouard  4947:        }
                   4948:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4949:        fprintf(ficresphtm,"</tr>\n");
                   4950:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4951:          if(iage <= iagemax)
                   4952:            fprintf(ficresp,"\n");
1.240     brouard  4953:        }
1.251     brouard  4954:        if(first==1)
                   4955:          printf("Others in log...\n");
                   4956:        fprintf(ficlog,"\n");
                   4957:       } /* end loop age iage */
1.265     brouard  4958:       
1.251     brouard  4959:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4960:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4961:        if(posproptt < 1.e-5){
1.265     brouard  4962:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4963:        }else{
1.265     brouard  4964:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4965:        }
1.226     brouard  4966:       }
1.251     brouard  4967:       fprintf(ficresphtm,"</tr>\n");
                   4968:       fprintf(ficresphtm,"</table>\n");
                   4969:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4970:       if(posproptt < 1.e-5){
1.251     brouard  4971:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4972:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4973:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4974:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4975:        invalidvarcomb[j1]=1;
1.226     brouard  4976:       }else{
1.251     brouard  4977:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4978:        invalidvarcomb[j1]=0;
1.226     brouard  4979:       }
1.251     brouard  4980:       fprintf(ficresphtmfr,"</table>\n");
                   4981:       fprintf(ficlog,"\n");
                   4982:       if(j!=0){
                   4983:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4984:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4985:          for(k=1; k <=(nlstate+ndeath); k++){
                   4986:            if (k != i) {
1.265     brouard  4987:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4988:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4989:                  if(j1==1){ /* All dummy covariates to zero */
                   4990:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4991:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4992:                    printf("%d%d ",i,k);
                   4993:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4994:                    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]));
                   4995:                    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]));
                   4996:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4997:                  }
1.253     brouard  4998:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4999:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5000:                    x[iage]= (double)iage;
                   5001:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5002:                    /* 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  5003:                  }
1.268     brouard  5004:                  /* Some are not finite, but linreg will ignore these ages */
                   5005:                  no=0;
1.253     brouard  5006:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5007:                  pstart[s1]=b;
                   5008:                  pstart[s1-1]=a;
1.252     brouard  5009:                }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 */ 
                   5010:                  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]);
                   5011:                  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  5012:                  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  5013:                  printf("%d%d ",i,k);
                   5014:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5015:                  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  5016:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5017:                  ;
                   5018:                }
                   5019:                /* printf("%12.7f )", param[i][jj][k]); */
                   5020:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5021:                s1++; 
1.251     brouard  5022:              } /* end jj */
                   5023:            } /* end k!= i */
                   5024:          } /* end k */
1.265     brouard  5025:        } /* end i, s1 */
1.251     brouard  5026:       } /* end j !=0 */
                   5027:     } /* end selected combination of covariate j1 */
                   5028:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5029:       printf("#Freqsummary: Starting values for the constants:\n");
                   5030:       fprintf(ficlog,"\n");
1.265     brouard  5031:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5032:        for(k=1; k <=(nlstate+ndeath); k++){
                   5033:          if (k != i) {
                   5034:            printf("%d%d ",i,k);
                   5035:            fprintf(ficlog,"%d%d ",i,k);
                   5036:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5037:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5038:              if(jj==1){ /* Age has to be done */
1.265     brouard  5039:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5040:                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]));
                   5041:                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  5042:              }
                   5043:              /* printf("%12.7f )", param[i][jj][k]); */
                   5044:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5045:              s1++; 
1.250     brouard  5046:            }
1.251     brouard  5047:            printf("\n");
                   5048:            fprintf(ficlog,"\n");
1.250     brouard  5049:          }
                   5050:        }
1.284     brouard  5051:       } /* end of state i */
1.251     brouard  5052:       printf("#Freqsummary\n");
                   5053:       fprintf(ficlog,"\n");
1.265     brouard  5054:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5055:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5056:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5057:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5058:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5059:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5060:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5061:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5062:          /* } */
                   5063:        }
1.265     brouard  5064:       } /* end loop s1 */
1.251     brouard  5065:       
                   5066:       printf("\n");
                   5067:       fprintf(ficlog,"\n");
                   5068:     } /* end j=0 */
1.249     brouard  5069:   } /* end j */
1.252     brouard  5070: 
1.253     brouard  5071:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5072:     for(i=1, jk=1; i <=nlstate; i++){
                   5073:       for(j=1; j <=nlstate+ndeath; j++){
                   5074:        if(j!=i){
                   5075:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5076:          printf("%1d%1d",i,j);
                   5077:          fprintf(ficparo,"%1d%1d",i,j);
                   5078:          for(k=1; k<=ncovmodel;k++){
                   5079:            /*    printf(" %lf",param[i][j][k]); */
                   5080:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5081:            p[jk]=pstart[jk];
                   5082:            printf(" %f ",pstart[jk]);
                   5083:            fprintf(ficparo," %f ",pstart[jk]);
                   5084:            jk++;
                   5085:          }
                   5086:          printf("\n");
                   5087:          fprintf(ficparo,"\n");
                   5088:        }
                   5089:       }
                   5090:     }
                   5091:   } /* end mle=-2 */
1.226     brouard  5092:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5093:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5094:   
1.226     brouard  5095:   fclose(ficresp);
                   5096:   fclose(ficresphtm);
                   5097:   fclose(ficresphtmfr);
1.283     brouard  5098:   free_vector(idq,1,nqfveff);
1.226     brouard  5099:   free_vector(meanq,1,nqfveff);
1.284     brouard  5100:   free_vector(stdq,1,nqfveff);
1.226     brouard  5101:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5102:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5103:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5104:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5105:   free_vector(pospropt,1,nlstate);
                   5106:   free_vector(posprop,1,nlstate);
1.251     brouard  5107:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5108:   free_vector(pp,1,nlstate);
                   5109:   /* End of freqsummary */
                   5110: }
1.126     brouard  5111: 
1.268     brouard  5112: /* Simple linear regression */
                   5113: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5114: 
                   5115:   /* y=a+bx regression */
                   5116:   double   sumx = 0.0;                        /* sum of x                      */
                   5117:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5118:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5119:   double   sumy = 0.0;                        /* sum of y                      */
                   5120:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5121:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5122:   double yhat;
                   5123:   
                   5124:   double denom=0;
                   5125:   int i;
                   5126:   int ne=*no;
                   5127:   
                   5128:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5129:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5130:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5131:       continue;
                   5132:     }
                   5133:     ne=ne+1;
                   5134:     sumx  += x[i];       
                   5135:     sumx2 += x[i]*x[i];  
                   5136:     sumxy += x[i] * y[i];
                   5137:     sumy  += y[i];      
                   5138:     sumy2 += y[i]*y[i]; 
                   5139:     denom = (ne * sumx2 - sumx*sumx);
                   5140:     /* 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); */
                   5141:   } 
                   5142:   
                   5143:   denom = (ne * sumx2 - sumx*sumx);
                   5144:   if (denom == 0) {
                   5145:     // vertical, slope m is infinity
                   5146:     *b = INFINITY;
                   5147:     *a = 0;
                   5148:     if (r) *r = 0;
                   5149:     return 1;
                   5150:   }
                   5151:   
                   5152:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5153:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5154:   if (r!=NULL) {
                   5155:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5156:       sqrt((sumx2 - sumx*sumx/ne) *
                   5157:           (sumy2 - sumy*sumy/ne));
                   5158:   }
                   5159:   *no=ne;
                   5160:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5161:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5162:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5163:       continue;
                   5164:     }
                   5165:     ne=ne+1;
                   5166:     yhat = y[i] - *a -*b* x[i];
                   5167:     sume2  += yhat * yhat ;       
                   5168:     
                   5169:     denom = (ne * sumx2 - sumx*sumx);
                   5170:     /* 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); */
                   5171:   } 
                   5172:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5173:   *sa= *sb * sqrt(sumx2/ne);
                   5174:   
                   5175:   return 0; 
                   5176: }
                   5177: 
1.126     brouard  5178: /************ Prevalence ********************/
1.227     brouard  5179: 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)
                   5180: {  
                   5181:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5182:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5183:      We still use firstpass and lastpass as another selection.
                   5184:   */
1.126     brouard  5185:  
1.227     brouard  5186:   int i, m, jk, j1, bool, z1,j, iv;
                   5187:   int mi; /* Effective wave */
                   5188:   int iage;
                   5189:   double agebegin, ageend;
                   5190: 
                   5191:   double **prop;
                   5192:   double posprop; 
                   5193:   double  y2; /* in fractional years */
                   5194:   int iagemin, iagemax;
                   5195:   int first; /** to stop verbosity which is redirected to log file */
                   5196: 
                   5197:   iagemin= (int) agemin;
                   5198:   iagemax= (int) agemax;
                   5199:   /*pp=vector(1,nlstate);*/
1.251     brouard  5200:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5201:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5202:   j1=0;
1.222     brouard  5203:   
1.227     brouard  5204:   /*j=cptcoveff;*/
                   5205:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5206:   
1.288     brouard  5207:   first=0;
1.227     brouard  5208:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5209:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5210:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5211:        prop[i][iage]=0.0;
                   5212:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5213:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5214:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5215:     
                   5216:     for (i=1; i<=imx; i++) { /* Each individual */
                   5217:       bool=1;
                   5218:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5219:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5220:        m=mw[mi][i];
                   5221:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5222:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5223:        for (z1=1; z1<=cptcoveff; z1++){
                   5224:          if( Fixed[Tmodelind[z1]]==1){
                   5225:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5226:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5227:              bool=0;
                   5228:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5229:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5230:              bool=0;
                   5231:            }
                   5232:        }
                   5233:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5234:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5235:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5236:          if(m >=firstpass && m <=lastpass){
                   5237:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5238:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5239:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5240:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5241:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5242:                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); 
                   5243:                exit(1);
                   5244:              }
                   5245:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5246:                /*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]]);*/
                   5247:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5248:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5249:              } /* end valid statuses */ 
                   5250:            } /* end selection of dates */
                   5251:          } /* end selection of waves */
                   5252:        } /* end bool */
                   5253:       } /* end wave */
                   5254:     } /* end individual */
                   5255:     for(i=iagemin; i <= iagemax+3; i++){  
                   5256:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5257:        posprop += prop[jk][i]; 
                   5258:       } 
                   5259:       
                   5260:       for(jk=1; jk <=nlstate ; jk++){      
                   5261:        if( i <=  iagemax){ 
                   5262:          if(posprop>=1.e-5){ 
                   5263:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5264:          } else{
1.288     brouard  5265:            if(!first){
                   5266:              first=1;
1.266     brouard  5267:              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]);
                   5268:            }else{
1.288     brouard  5269:              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  5270:            }
                   5271:          }
                   5272:        } 
                   5273:       }/* end jk */ 
                   5274:     }/* end i */ 
1.222     brouard  5275:      /*} *//* end i1 */
1.227     brouard  5276:   } /* end j1 */
1.222     brouard  5277:   
1.227     brouard  5278:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5279:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5280:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5281: }  /* End of prevalence */
1.126     brouard  5282: 
                   5283: /************* Waves Concatenation ***************/
                   5284: 
                   5285: 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)
                   5286: {
1.298     brouard  5287:   /* 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  5288:      Death is a valid wave (if date is known).
                   5289:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5290:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5291:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5292:   */
1.126     brouard  5293: 
1.224     brouard  5294:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5295:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5296:      double sum=0., jmean=0.;*/
1.224     brouard  5297:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5298:   int j, k=0,jk, ju, jl;
                   5299:   double sum=0.;
                   5300:   first=0;
1.214     brouard  5301:   firstwo=0;
1.217     brouard  5302:   firsthree=0;
1.218     brouard  5303:   firstfour=0;
1.164     brouard  5304:   jmin=100000;
1.126     brouard  5305:   jmax=-1;
                   5306:   jmean=0.;
1.224     brouard  5307: 
                   5308: /* Treating live states */
1.214     brouard  5309:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5310:     mi=0;  /* First valid wave */
1.227     brouard  5311:     mli=0; /* Last valid wave */
1.309     brouard  5312:     m=firstpass;  /* Loop on waves */
                   5313:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5314:       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 */
                   5315:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5316:       }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  5317:        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  5318:        mli=m;
1.224     brouard  5319:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5320:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5321:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5322:       }
1.309     brouard  5323:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5324: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5325:        break;
1.224     brouard  5326: #else
1.309     brouard  5327:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){ /* case -2 (vital status unknown is warned later */
1.227     brouard  5328:          if(firsthree == 0){
1.302     brouard  5329:            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  5330:            firsthree=1;
                   5331:          }
1.302     brouard  5332:          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);
1.309     brouard  5333:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5334:          mli=m;
                   5335:        }
                   5336:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5337:          nbwarn++;
1.309     brouard  5338:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5339:            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);
                   5340:            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);
                   5341:          }
                   5342:          break;
                   5343:        }
                   5344:        break;
1.224     brouard  5345: #endif
1.227     brouard  5346:       }/* End m >= lastpass */
1.126     brouard  5347:     }/* end while */
1.224     brouard  5348: 
1.227     brouard  5349:     /* 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  5350:     /* After last pass */
1.224     brouard  5351: /* Treating death states */
1.214     brouard  5352:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5353:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5354:       /* } */
1.126     brouard  5355:       mi++;    /* Death is another wave */
                   5356:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5357:       /* Only death is a correct wave */
1.126     brouard  5358:       mw[mi][i]=m;
1.257     brouard  5359:     } /* else not in a death state */
1.224     brouard  5360: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5361:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5362:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5363:        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  5364:          nbwarn++;
                   5365:          if(firstfiv==0){
1.309     brouard  5366:            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  5367:            firstfiv=1;
                   5368:          }else{
1.309     brouard  5369:            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  5370:          }
1.309     brouard  5371:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5372:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5373:          nberr++;
                   5374:          if(firstwo==0){
1.309     brouard  5375:            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  5376:            firstwo=1;
                   5377:          }
1.309     brouard  5378:          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  5379:        }
1.257     brouard  5380:       }else{ /* if date of interview is unknown */
1.227     brouard  5381:        /* death is known but not confirmed by death status at any wave */
                   5382:        if(firstfour==0){
1.309     brouard  5383:          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  5384:          firstfour=1;
                   5385:        }
1.309     brouard  5386:        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  5387:       }
1.224     brouard  5388:     } /* end if date of death is known */
                   5389: #endif
1.309     brouard  5390:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5391:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5392:     if(mi==0){
                   5393:       nbwarn++;
                   5394:       if(first==0){
1.227     brouard  5395:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5396:        first=1;
1.126     brouard  5397:       }
                   5398:       if(first==1){
1.227     brouard  5399:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5400:       }
                   5401:     } /* end mi==0 */
                   5402:   } /* End individuals */
1.214     brouard  5403:   /* wav and mw are no more changed */
1.223     brouard  5404:        
1.214     brouard  5405:   
1.126     brouard  5406:   for(i=1; i<=imx; i++){
                   5407:     for(mi=1; mi<wav[i];mi++){
                   5408:       if (stepm <=0)
1.227     brouard  5409:        dh[mi][i]=1;
1.126     brouard  5410:       else{
1.260     brouard  5411:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5412:          if (agedc[i] < 2*AGESUP) {
                   5413:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5414:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5415:            else if(j<0){
                   5416:              nberr++;
                   5417:              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]);
                   5418:              j=1; /* Temporary Dangerous patch */
                   5419:              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);
                   5420:              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]);
                   5421:              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);
                   5422:            }
                   5423:            k=k+1;
                   5424:            if (j >= jmax){
                   5425:              jmax=j;
                   5426:              ijmax=i;
                   5427:            }
                   5428:            if (j <= jmin){
                   5429:              jmin=j;
                   5430:              ijmin=i;
                   5431:            }
                   5432:            sum=sum+j;
                   5433:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5434:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5435:          }
                   5436:        }
                   5437:        else{
                   5438:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5439: /*       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  5440:                                        
1.227     brouard  5441:          k=k+1;
                   5442:          if (j >= jmax) {
                   5443:            jmax=j;
                   5444:            ijmax=i;
                   5445:          }
                   5446:          else if (j <= jmin){
                   5447:            jmin=j;
                   5448:            ijmin=i;
                   5449:          }
                   5450:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5451:          /*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]);*/
                   5452:          if(j<0){
                   5453:            nberr++;
                   5454:            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]);
                   5455:            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]);
                   5456:          }
                   5457:          sum=sum+j;
                   5458:        }
                   5459:        jk= j/stepm;
                   5460:        jl= j -jk*stepm;
                   5461:        ju= j -(jk+1)*stepm;
                   5462:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5463:          if(jl==0){
                   5464:            dh[mi][i]=jk;
                   5465:            bh[mi][i]=0;
                   5466:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5467:                  * to avoid the price of an extra matrix product in likelihood */
                   5468:            dh[mi][i]=jk+1;
                   5469:            bh[mi][i]=ju;
                   5470:          }
                   5471:        }else{
                   5472:          if(jl <= -ju){
                   5473:            dh[mi][i]=jk;
                   5474:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5475:                                 * is higher than the multiple of stepm and negative otherwise.
                   5476:                                 */
                   5477:          }
                   5478:          else{
                   5479:            dh[mi][i]=jk+1;
                   5480:            bh[mi][i]=ju;
                   5481:          }
                   5482:          if(dh[mi][i]==0){
                   5483:            dh[mi][i]=1; /* At least one step */
                   5484:            bh[mi][i]=ju; /* At least one step */
                   5485:            /*  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);*/
                   5486:          }
                   5487:        } /* end if mle */
1.126     brouard  5488:       }
                   5489:     } /* end wave */
                   5490:   }
                   5491:   jmean=sum/k;
                   5492:   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  5493:   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  5494: }
1.126     brouard  5495: 
                   5496: /*********** Tricode ****************************/
1.220     brouard  5497:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5498:  {
                   5499:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5500:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5501:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5502:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5503:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5504:     */
1.130     brouard  5505: 
1.242     brouard  5506:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5507:    int modmaxcovj=0; /* Modality max of covariates j */
                   5508:    int cptcode=0; /* Modality max of covariates j */
                   5509:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5510: 
                   5511: 
1.242     brouard  5512:    /* cptcoveff=0;  */
                   5513:    /* *cptcov=0; */
1.126     brouard  5514:  
1.242     brouard  5515:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5516:    for (k=1; k <= maxncov; k++)
                   5517:      for(j=1; j<=2; j++)
                   5518:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5519: 
1.242     brouard  5520:    /* Loop on covariates without age and products and no quantitative variable */
                   5521:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5522:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5523:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5524:        switch(Fixed[k]) {
                   5525:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5526:         modmaxcovj=0;
                   5527:         modmincovj=0;
1.242     brouard  5528:         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*/
                   5529:           ij=(int)(covar[Tvar[k]][i]);
                   5530:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5531:            * If product of Vn*Vm, still boolean *:
                   5532:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5533:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5534:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5535:              modality of the nth covariate of individual i. */
                   5536:           if (ij > modmaxcovj)
                   5537:             modmaxcovj=ij; 
                   5538:           else if (ij < modmincovj) 
                   5539:             modmincovj=ij; 
1.287     brouard  5540:           if (ij <0 || ij >1 ){
1.311     brouard  5541:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5542:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5543:             fflush(ficlog);
                   5544:             exit(1);
1.287     brouard  5545:           }
                   5546:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5547:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5548:             exit(1);
                   5549:           }else
                   5550:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5551:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5552:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5553:           /* getting the maximum value of the modality of the covariate
                   5554:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5555:              female ies 1, then modmaxcovj=1.
                   5556:           */
                   5557:         } /* end for loop on individuals i */
                   5558:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5559:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5560:         cptcode=modmaxcovj;
                   5561:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5562:         /*for (i=0; i<=cptcode; i++) {*/
                   5563:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5564:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5565:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5566:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5567:             if( j != -1){
                   5568:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5569:                                  covariate for which somebody answered excluding 
                   5570:                                  undefined. Usually 2: 0 and 1. */
                   5571:             }
                   5572:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5573:                                     covariate for which somebody answered including 
                   5574:                                     undefined. Usually 3: -1, 0 and 1. */
                   5575:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5576:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5577:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5578:                        
1.242     brouard  5579:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5580:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5581:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5582:         /* modmincovj=3; modmaxcovj = 7; */
                   5583:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5584:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5585:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5586:         /* nbcode[Tvar[j]][ij]=k; */
                   5587:         /* nbcode[Tvar[j]][1]=0; */
                   5588:         /* nbcode[Tvar[j]][2]=1; */
                   5589:         /* nbcode[Tvar[j]][3]=2; */
                   5590:         /* To be continued (not working yet). */
                   5591:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5592: 
                   5593:         /* 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*/
                   5594:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5595:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5596:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5597:         /*, could be restored in the future */
                   5598:         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  5599:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5600:             break;
                   5601:           }
                   5602:           ij++;
1.287     brouard  5603:           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  5604:           cptcode = ij; /* New max modality for covar j */
                   5605:         } /* end of loop on modality i=-1 to 1 or more */
                   5606:         break;
                   5607:        case 1: /* Testing on varying covariate, could be simple and
                   5608:                * should look at waves or product of fixed *
                   5609:                * varying. No time to test -1, assuming 0 and 1 only */
                   5610:         ij=0;
                   5611:         for(i=0; i<=1;i++){
                   5612:           nbcode[Tvar[k]][++ij]=i;
                   5613:         }
                   5614:         break;
                   5615:        default:
                   5616:         break;
                   5617:        } /* end switch */
                   5618:      } /* end dummy test */
1.311     brouard  5619:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5620:        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*/
                   5621:         if(isnan(covar[Tvar[k]][i])){
                   5622:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5623:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5624:           fflush(ficlog);
                   5625:           exit(1);
                   5626:          }
                   5627:        }
                   5628:      }
1.287     brouard  5629:    } /* 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  5630:   
                   5631:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5632:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5633:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5634:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5635:      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 */ 
                   5636:      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 */
                   5637:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5638:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5639:   
                   5640:    ij=0;
                   5641:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5642:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5643:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5644:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5645:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5646:        /* If product not in single variable we don't print results */
                   5647:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5648:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5649:        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*/
                   5650:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5651:        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 */
                   5652:        if(Fixed[k]!=0)
                   5653:         anyvaryingduminmodel=1;
                   5654:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5655:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5656:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5657:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5658:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5659:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5660:      } 
                   5661:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5662:    /* ij--; */
                   5663:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5664:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5665:                * because they can be excluded from the model and real
                   5666:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5667:    for(j=ij+1; j<= cptcovt; j++){
                   5668:      Tvaraff[j]=0;
                   5669:      Tmodelind[j]=0;
                   5670:    }
                   5671:    for(j=ntveff+1; j<= cptcovt; j++){
                   5672:      TmodelInvind[j]=0;
                   5673:    }
                   5674:    /* To be sorted */
                   5675:    ;
                   5676:  }
1.126     brouard  5677: 
1.145     brouard  5678: 
1.126     brouard  5679: /*********** Health Expectancies ****************/
                   5680: 
1.235     brouard  5681:  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  5682: 
                   5683: {
                   5684:   /* Health expectancies, no variances */
1.164     brouard  5685:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5686:   int nhstepma, nstepma; /* Decreasing with age */
                   5687:   double age, agelim, hf;
                   5688:   double ***p3mat;
                   5689:   double eip;
                   5690: 
1.238     brouard  5691:   /* pstamp(ficreseij); */
1.126     brouard  5692:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5693:   fprintf(ficreseij,"# Age");
                   5694:   for(i=1; i<=nlstate;i++){
                   5695:     for(j=1; j<=nlstate;j++){
                   5696:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5697:     }
                   5698:     fprintf(ficreseij," e%1d. ",i);
                   5699:   }
                   5700:   fprintf(ficreseij,"\n");
                   5701: 
                   5702:   
                   5703:   if(estepm < stepm){
                   5704:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5705:   }
                   5706:   else  hstepm=estepm;   
                   5707:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5708:    * This is mainly to measure the difference between two models: for example
                   5709:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5710:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5711:    * progression in between and thus overestimating or underestimating according
                   5712:    * to the curvature of the survival function. If, for the same date, we 
                   5713:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5714:    * to compare the new estimate of Life expectancy with the same linear 
                   5715:    * hypothesis. A more precise result, taking into account a more precise
                   5716:    * curvature will be obtained if estepm is as small as stepm. */
                   5717: 
                   5718:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5719:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5720:      nhstepm is the number of hstepm from age to agelim 
                   5721:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5722:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5723:      and note for a fixed period like estepm months */
                   5724:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5725:      survival function given by stepm (the optimization length). Unfortunately it
                   5726:      means that if the survival funtion is printed only each two years of age and if
                   5727:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5728:      results. So we changed our mind and took the option of the best precision.
                   5729:   */
                   5730:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5731: 
                   5732:   agelim=AGESUP;
                   5733:   /* If stepm=6 months */
                   5734:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5735:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5736:     
                   5737: /* nhstepm age range expressed in number of stepm */
                   5738:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5739:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5740:   /* if (stepm >= YEARM) hstepm=1;*/
                   5741:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5742:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5743: 
                   5744:   for (age=bage; age<=fage; age ++){ 
                   5745:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5746:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5747:     /* if (stepm >= YEARM) hstepm=1;*/
                   5748:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5749: 
                   5750:     /* If stepm=6 months */
                   5751:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5752:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5753:     
1.235     brouard  5754:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5755:     
                   5756:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5757:     
                   5758:     printf("%d|",(int)age);fflush(stdout);
                   5759:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5760:     
                   5761:     /* Computing expectancies */
                   5762:     for(i=1; i<=nlstate;i++)
                   5763:       for(j=1; j<=nlstate;j++)
                   5764:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5765:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5766:          
                   5767:          /* 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]);*/
                   5768: 
                   5769:        }
                   5770: 
                   5771:     fprintf(ficreseij,"%3.0f",age );
                   5772:     for(i=1; i<=nlstate;i++){
                   5773:       eip=0;
                   5774:       for(j=1; j<=nlstate;j++){
                   5775:        eip +=eij[i][j][(int)age];
                   5776:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5777:       }
                   5778:       fprintf(ficreseij,"%9.4f", eip );
                   5779:     }
                   5780:     fprintf(ficreseij,"\n");
                   5781:     
                   5782:   }
                   5783:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5784:   printf("\n");
                   5785:   fprintf(ficlog,"\n");
                   5786:   
                   5787: }
                   5788: 
1.235     brouard  5789:  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  5790: 
                   5791: {
                   5792:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5793:      to initial status i, ei. .
1.126     brouard  5794:   */
                   5795:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5796:   int nhstepma, nstepma; /* Decreasing with age */
                   5797:   double age, agelim, hf;
                   5798:   double ***p3matp, ***p3matm, ***varhe;
                   5799:   double **dnewm,**doldm;
                   5800:   double *xp, *xm;
                   5801:   double **gp, **gm;
                   5802:   double ***gradg, ***trgradg;
                   5803:   int theta;
                   5804: 
                   5805:   double eip, vip;
                   5806: 
                   5807:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5808:   xp=vector(1,npar);
                   5809:   xm=vector(1,npar);
                   5810:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5811:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5812:   
                   5813:   pstamp(ficresstdeij);
                   5814:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5815:   fprintf(ficresstdeij,"# Age");
                   5816:   for(i=1; i<=nlstate;i++){
                   5817:     for(j=1; j<=nlstate;j++)
                   5818:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5819:     fprintf(ficresstdeij," e%1d. ",i);
                   5820:   }
                   5821:   fprintf(ficresstdeij,"\n");
                   5822: 
                   5823:   pstamp(ficrescveij);
                   5824:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5825:   fprintf(ficrescveij,"# Age");
                   5826:   for(i=1; i<=nlstate;i++)
                   5827:     for(j=1; j<=nlstate;j++){
                   5828:       cptj= (j-1)*nlstate+i;
                   5829:       for(i2=1; i2<=nlstate;i2++)
                   5830:        for(j2=1; j2<=nlstate;j2++){
                   5831:          cptj2= (j2-1)*nlstate+i2;
                   5832:          if(cptj2 <= cptj)
                   5833:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5834:        }
                   5835:     }
                   5836:   fprintf(ficrescveij,"\n");
                   5837:   
                   5838:   if(estepm < stepm){
                   5839:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5840:   }
                   5841:   else  hstepm=estepm;   
                   5842:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5843:    * This is mainly to measure the difference between two models: for example
                   5844:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5845:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5846:    * progression in between and thus overestimating or underestimating according
                   5847:    * to the curvature of the survival function. If, for the same date, we 
                   5848:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5849:    * to compare the new estimate of Life expectancy with the same linear 
                   5850:    * hypothesis. A more precise result, taking into account a more precise
                   5851:    * curvature will be obtained if estepm is as small as stepm. */
                   5852: 
                   5853:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5854:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5855:      nhstepm is the number of hstepm from age to agelim 
                   5856:      nstepm is the number of stepm from age to agelin. 
                   5857:      Look at hpijx to understand the reason of that which relies in memory size
                   5858:      and note for a fixed period like estepm months */
                   5859:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5860:      survival function given by stepm (the optimization length). Unfortunately it
                   5861:      means that if the survival funtion is printed only each two years of age and if
                   5862:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5863:      results. So we changed our mind and took the option of the best precision.
                   5864:   */
                   5865:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5866: 
                   5867:   /* If stepm=6 months */
                   5868:   /* nhstepm age range expressed in number of stepm */
                   5869:   agelim=AGESUP;
                   5870:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5871:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5872:   /* if (stepm >= YEARM) hstepm=1;*/
                   5873:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5874:   
                   5875:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5876:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5877:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5878:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5879:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5880:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5881: 
                   5882:   for (age=bage; age<=fage; age ++){ 
                   5883:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5884:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5885:     /* if (stepm >= YEARM) hstepm=1;*/
                   5886:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5887:                
1.126     brouard  5888:     /* If stepm=6 months */
                   5889:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5890:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5891:     
                   5892:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5893:                
1.126     brouard  5894:     /* Computing  Variances of health expectancies */
                   5895:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5896:        decrease memory allocation */
                   5897:     for(theta=1; theta <=npar; theta++){
                   5898:       for(i=1; i<=npar; i++){ 
1.222     brouard  5899:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5900:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5901:       }
1.235     brouard  5902:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5903:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5904:                        
1.126     brouard  5905:       for(j=1; j<= nlstate; j++){
1.222     brouard  5906:        for(i=1; i<=nlstate; i++){
                   5907:          for(h=0; h<=nhstepm-1; h++){
                   5908:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5909:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5910:          }
                   5911:        }
1.126     brouard  5912:       }
1.218     brouard  5913:                        
1.126     brouard  5914:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5915:        for(h=0; h<=nhstepm-1; h++){
                   5916:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5917:        }
1.126     brouard  5918:     }/* End theta */
                   5919:     
                   5920:     
                   5921:     for(h=0; h<=nhstepm-1; h++)
                   5922:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5923:        for(theta=1; theta <=npar; theta++)
                   5924:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5925:     
1.218     brouard  5926:                
1.222     brouard  5927:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5928:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5929:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5930:                
1.222     brouard  5931:     printf("%d|",(int)age);fflush(stdout);
                   5932:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5933:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5934:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5935:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5936:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5937:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5938:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5939:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5940:       }
                   5941:     }
1.218     brouard  5942:                
1.126     brouard  5943:     /* Computing expectancies */
1.235     brouard  5944:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5945:     for(i=1; i<=nlstate;i++)
                   5946:       for(j=1; j<=nlstate;j++)
1.222     brouard  5947:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5948:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5949:                                        
1.222     brouard  5950:          /* 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  5951:                                        
1.222     brouard  5952:        }
1.269     brouard  5953: 
                   5954:     /* Standard deviation of expectancies ij */                
1.126     brouard  5955:     fprintf(ficresstdeij,"%3.0f",age );
                   5956:     for(i=1; i<=nlstate;i++){
                   5957:       eip=0.;
                   5958:       vip=0.;
                   5959:       for(j=1; j<=nlstate;j++){
1.222     brouard  5960:        eip += eij[i][j][(int)age];
                   5961:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5962:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5963:        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  5964:       }
                   5965:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5966:     }
                   5967:     fprintf(ficresstdeij,"\n");
1.218     brouard  5968:                
1.269     brouard  5969:     /* Variance of expectancies ij */          
1.126     brouard  5970:     fprintf(ficrescveij,"%3.0f",age );
                   5971:     for(i=1; i<=nlstate;i++)
                   5972:       for(j=1; j<=nlstate;j++){
1.222     brouard  5973:        cptj= (j-1)*nlstate+i;
                   5974:        for(i2=1; i2<=nlstate;i2++)
                   5975:          for(j2=1; j2<=nlstate;j2++){
                   5976:            cptj2= (j2-1)*nlstate+i2;
                   5977:            if(cptj2 <= cptj)
                   5978:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5979:          }
1.126     brouard  5980:       }
                   5981:     fprintf(ficrescveij,"\n");
1.218     brouard  5982:                
1.126     brouard  5983:   }
                   5984:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5985:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5986:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5987:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5988:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5989:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5990:   printf("\n");
                   5991:   fprintf(ficlog,"\n");
1.218     brouard  5992:        
1.126     brouard  5993:   free_vector(xm,1,npar);
                   5994:   free_vector(xp,1,npar);
                   5995:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5996:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5997:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5998: }
1.218     brouard  5999:  
1.126     brouard  6000: /************ Variance ******************/
1.235     brouard  6001:  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  6002:  {
1.279     brouard  6003:    /** Variance of health expectancies 
                   6004:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6005:     * double **newm;
                   6006:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6007:     */
1.218     brouard  6008:   
                   6009:    /* int movingaverage(); */
                   6010:    double **dnewm,**doldm;
                   6011:    double **dnewmp,**doldmp;
                   6012:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6013:    int first=0;
1.218     brouard  6014:    int k;
                   6015:    double *xp;
1.279     brouard  6016:    double **gp, **gm;  /**< for var eij */
                   6017:    double ***gradg, ***trgradg; /**< for var eij */
                   6018:    double **gradgp, **trgradgp; /**< for var p point j */
                   6019:    double *gpp, *gmp; /**< for var p point j */
                   6020:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6021:    double ***p3mat;
                   6022:    double age,agelim, hf;
                   6023:    /* double ***mobaverage; */
                   6024:    int theta;
                   6025:    char digit[4];
                   6026:    char digitp[25];
                   6027: 
                   6028:    char fileresprobmorprev[FILENAMELENGTH];
                   6029: 
                   6030:    if(popbased==1){
                   6031:      if(mobilav!=0)
                   6032:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6033:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6034:    }
                   6035:    else 
                   6036:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6037: 
1.218     brouard  6038:    /* if (mobilav!=0) { */
                   6039:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6040:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6041:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6042:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6043:    /*   } */
                   6044:    /* } */
                   6045: 
                   6046:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6047:    sprintf(digit,"%-d",ij);
                   6048:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6049:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6050:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6051:    strcat(fileresprobmorprev,fileresu);
                   6052:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6053:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6054:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6055:    }
                   6056:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6057:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6058:    pstamp(ficresprobmorprev);
                   6059:    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  6060:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6061:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6062:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6063:    }
                   6064:    for(j=1;j<=cptcoveff;j++) 
                   6065:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   6066:    fprintf(ficresprobmorprev,"\n");
                   6067: 
1.218     brouard  6068:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6069:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6070:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6071:      for(i=1; i<=nlstate;i++)
                   6072:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6073:    }  
                   6074:    fprintf(ficresprobmorprev,"\n");
                   6075:   
                   6076:    fprintf(ficgp,"\n# Routine varevsij");
                   6077:    fprintf(ficgp,"\nunset title \n");
                   6078:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6079:    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");
                   6080:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6081: 
1.218     brouard  6082:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6083:    pstamp(ficresvij);
                   6084:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6085:    if(popbased==1)
                   6086:      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);
                   6087:    else
                   6088:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6089:    fprintf(ficresvij,"# Age");
                   6090:    for(i=1; i<=nlstate;i++)
                   6091:      for(j=1; j<=nlstate;j++)
                   6092:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6093:    fprintf(ficresvij,"\n");
                   6094: 
                   6095:    xp=vector(1,npar);
                   6096:    dnewm=matrix(1,nlstate,1,npar);
                   6097:    doldm=matrix(1,nlstate,1,nlstate);
                   6098:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6099:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6100: 
                   6101:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6102:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6103:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6104:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6105:   
1.218     brouard  6106:    if(estepm < stepm){
                   6107:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6108:    }
                   6109:    else  hstepm=estepm;   
                   6110:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6111:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6112:       nhstepm is the number of hstepm from age to agelim 
                   6113:       nstepm is the number of stepm from age to agelim. 
                   6114:       Look at function hpijx to understand why because of memory size limitations, 
                   6115:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6116:       survival function given by stepm (the optimization length). Unfortunately it
                   6117:       means that if the survival funtion is printed every two years of age and if
                   6118:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6119:       results. So we changed our mind and took the option of the best precision.
                   6120:    */
                   6121:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6122:    agelim = AGESUP;
                   6123:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6124:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6125:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6126:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6127:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6128:      gp=matrix(0,nhstepm,1,nlstate);
                   6129:      gm=matrix(0,nhstepm,1,nlstate);
                   6130:                
                   6131:                
                   6132:      for(theta=1; theta <=npar; theta++){
                   6133:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6134:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6135:        }
1.279     brouard  6136:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6137:        * returns into prlim .
1.288     brouard  6138:        */
1.242     brouard  6139:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6140: 
                   6141:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6142:        if (popbased==1) {
                   6143:         if(mobilav ==0){
                   6144:           for(i=1; i<=nlstate;i++)
                   6145:             prlim[i][i]=probs[(int)age][i][ij];
                   6146:         }else{ /* mobilav */ 
                   6147:           for(i=1; i<=nlstate;i++)
                   6148:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6149:         }
                   6150:        }
1.295     brouard  6151:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6152:        */                      
                   6153:        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  6154:        /**< 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  6155:        * at horizon h in state j including mortality.
                   6156:        */
1.218     brouard  6157:        for(j=1; j<= nlstate; j++){
                   6158:         for(h=0; h<=nhstepm; h++){
                   6159:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6160:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6161:         }
                   6162:        }
1.279     brouard  6163:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6164:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6165:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6166:        */
                   6167:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6168:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6169:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6170:        }
                   6171:        
                   6172:        /* Again with minus shift */
1.218     brouard  6173:                        
                   6174:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6175:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6176: 
1.242     brouard  6177:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6178:                        
                   6179:        if (popbased==1) {
                   6180:         if(mobilav ==0){
                   6181:           for(i=1; i<=nlstate;i++)
                   6182:             prlim[i][i]=probs[(int)age][i][ij];
                   6183:         }else{ /* mobilav */ 
                   6184:           for(i=1; i<=nlstate;i++)
                   6185:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6186:         }
                   6187:        }
                   6188:                        
1.235     brouard  6189:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6190:                        
                   6191:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6192:         for(h=0; h<=nhstepm; h++){
                   6193:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6194:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6195:         }
                   6196:        }
                   6197:        /* This for computing probability of death (h=1 means
                   6198:          computed over hstepm matrices product = hstepm*stepm months) 
                   6199:          as a weighted average of prlim.
                   6200:        */
                   6201:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6202:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6203:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6204:        }    
1.279     brouard  6205:        /* end shifting computations */
                   6206: 
                   6207:        /**< Computing gradient matrix at horizon h 
                   6208:        */
1.218     brouard  6209:        for(j=1; j<= nlstate; j++) /* vareij */
                   6210:         for(h=0; h<=nhstepm; h++){
                   6211:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6212:         }
1.279     brouard  6213:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6214:        */
                   6215:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6216:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6217:        }
                   6218:                        
                   6219:      } /* End theta */
1.279     brouard  6220:      
                   6221:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6222:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6223:                
                   6224:      for(h=0; h<=nhstepm; h++) /* veij */
                   6225:        for(j=1; j<=nlstate;j++)
                   6226:         for(theta=1; theta <=npar; theta++)
                   6227:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6228:                
                   6229:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6230:        for(theta=1; theta <=npar; theta++)
                   6231:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6232:      /**< as well as its transposed matrix 
                   6233:       */               
1.218     brouard  6234:                
                   6235:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6236:      for(i=1;i<=nlstate;i++)
                   6237:        for(j=1;j<=nlstate;j++)
                   6238:         vareij[i][j][(int)age] =0.;
1.279     brouard  6239: 
                   6240:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6241:       * and k (nhstepm) formula 15 of article
                   6242:       * Lievre-Brouard-Heathcote
                   6243:       */
                   6244:      
1.218     brouard  6245:      for(h=0;h<=nhstepm;h++){
                   6246:        for(k=0;k<=nhstepm;k++){
                   6247:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6248:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6249:         for(i=1;i<=nlstate;i++)
                   6250:           for(j=1;j<=nlstate;j++)
                   6251:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6252:        }
                   6253:      }
                   6254:                
1.279     brouard  6255:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6256:       * p.j overall mortality formula 49 but computed directly because
                   6257:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6258:       * wix is independent of theta.
                   6259:       */
1.218     brouard  6260:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6261:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6262:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6263:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6264:         varppt[j][i]=doldmp[j][i];
                   6265:      /* end ppptj */
                   6266:      /*  x centered again */
                   6267:                
1.242     brouard  6268:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6269:                
                   6270:      if (popbased==1) {
                   6271:        if(mobilav ==0){
                   6272:         for(i=1; i<=nlstate;i++)
                   6273:           prlim[i][i]=probs[(int)age][i][ij];
                   6274:        }else{ /* mobilav */ 
                   6275:         for(i=1; i<=nlstate;i++)
                   6276:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6277:        }
                   6278:      }
                   6279:                
                   6280:      /* This for computing probability of death (h=1 means
                   6281:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6282:        as a weighted average of prlim.
                   6283:      */
1.235     brouard  6284:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6285:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6286:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6287:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6288:      }    
                   6289:      /* end probability of death */
                   6290:                
                   6291:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6292:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6293:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6294:        for(i=1; i<=nlstate;i++){
                   6295:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6296:        }
                   6297:      } 
                   6298:      fprintf(ficresprobmorprev,"\n");
                   6299:                
                   6300:      fprintf(ficresvij,"%.0f ",age );
                   6301:      for(i=1; i<=nlstate;i++)
                   6302:        for(j=1; j<=nlstate;j++){
                   6303:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6304:        }
                   6305:      fprintf(ficresvij,"\n");
                   6306:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6307:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6308:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6309:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6310:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6311:    } /* End age */
                   6312:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6313:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6314:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6315:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6316:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6317:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6318:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6319:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6320:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6321:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6322:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6323:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6324:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6325:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6326:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6327:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6328:    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);
                   6329:    /*  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  6330:     */
1.218     brouard  6331:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6332:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6333: 
1.218     brouard  6334:    free_vector(xp,1,npar);
                   6335:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6336:    free_matrix(dnewm,1,nlstate,1,npar);
                   6337:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6338:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6339:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6340:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6341:    fclose(ficresprobmorprev);
                   6342:    fflush(ficgp);
                   6343:    fflush(fichtm); 
                   6344:  }  /* end varevsij */
1.126     brouard  6345: 
                   6346: /************ Variance of prevlim ******************/
1.269     brouard  6347:  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  6348: {
1.205     brouard  6349:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6350:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6351: 
1.268     brouard  6352:   double **dnewmpar,**doldm;
1.126     brouard  6353:   int i, j, nhstepm, hstepm;
                   6354:   double *xp;
                   6355:   double *gp, *gm;
                   6356:   double **gradg, **trgradg;
1.208     brouard  6357:   double **mgm, **mgp;
1.126     brouard  6358:   double age,agelim;
                   6359:   int theta;
                   6360:   
                   6361:   pstamp(ficresvpl);
1.288     brouard  6362:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6363:   fprintf(ficresvpl,"# Age ");
                   6364:   if(nresult >=1)
                   6365:     fprintf(ficresvpl," Result# ");
1.126     brouard  6366:   for(i=1; i<=nlstate;i++)
                   6367:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6368:   fprintf(ficresvpl,"\n");
                   6369: 
                   6370:   xp=vector(1,npar);
1.268     brouard  6371:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6372:   doldm=matrix(1,nlstate,1,nlstate);
                   6373:   
                   6374:   hstepm=1*YEARM; /* Every year of age */
                   6375:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6376:   agelim = AGESUP;
                   6377:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6378:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6379:     if (stepm >= YEARM) hstepm=1;
                   6380:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6381:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6382:     mgp=matrix(1,npar,1,nlstate);
                   6383:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6384:     gp=vector(1,nlstate);
                   6385:     gm=vector(1,nlstate);
                   6386: 
                   6387:     for(theta=1; theta <=npar; theta++){
                   6388:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6389:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6390:       }
1.288     brouard  6391:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6392:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6393:       /* else */
                   6394:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6395:       for(i=1;i<=nlstate;i++){
1.126     brouard  6396:        gp[i] = prlim[i][i];
1.208     brouard  6397:        mgp[theta][i] = prlim[i][i];
                   6398:       }
1.126     brouard  6399:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6400:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6401:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6402:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6403:       /* else */
                   6404:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6405:       for(i=1;i<=nlstate;i++){
1.126     brouard  6406:        gm[i] = prlim[i][i];
1.208     brouard  6407:        mgm[theta][i] = prlim[i][i];
                   6408:       }
1.126     brouard  6409:       for(i=1;i<=nlstate;i++)
                   6410:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6411:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6412:     } /* End theta */
                   6413: 
                   6414:     trgradg =matrix(1,nlstate,1,npar);
                   6415: 
                   6416:     for(j=1; j<=nlstate;j++)
                   6417:       for(theta=1; theta <=npar; theta++)
                   6418:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6419:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6420:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6421:     /*   for(j=1; j<=nlstate;j++){ */
                   6422:     /*         printf(" %d ",j); */
                   6423:     /*         for(theta=1; theta <=npar; theta++) */
                   6424:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6425:     /*         printf("\n "); */
                   6426:     /*   } */
                   6427:     /* } */
                   6428:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6429:     /*   printf("\n gradg %d ",(int)age); */
                   6430:     /*   for(j=1; j<=nlstate;j++){ */
                   6431:     /*         printf("%d ",j); */
                   6432:     /*         for(theta=1; theta <=npar; theta++) */
                   6433:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6434:     /*         printf("\n "); */
                   6435:     /*   } */
                   6436:     /* } */
1.126     brouard  6437: 
                   6438:     for(i=1;i<=nlstate;i++)
                   6439:       varpl[i][(int)age] =0.;
1.209     brouard  6440:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6441:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6442:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6443:     }else{
1.268     brouard  6444:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6445:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6446:     }
1.126     brouard  6447:     for(i=1;i<=nlstate;i++)
                   6448:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6449: 
                   6450:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6451:     if(nresult >=1)
                   6452:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6453:     for(i=1; i<=nlstate;i++){
1.126     brouard  6454:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6455:       /* for(j=1;j<=nlstate;j++) */
                   6456:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6457:     }
1.126     brouard  6458:     fprintf(ficresvpl,"\n");
                   6459:     free_vector(gp,1,nlstate);
                   6460:     free_vector(gm,1,nlstate);
1.208     brouard  6461:     free_matrix(mgm,1,npar,1,nlstate);
                   6462:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6463:     free_matrix(gradg,1,npar,1,nlstate);
                   6464:     free_matrix(trgradg,1,nlstate,1,npar);
                   6465:   } /* End age */
                   6466: 
                   6467:   free_vector(xp,1,npar);
                   6468:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6469:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6470: 
                   6471: }
                   6472: 
                   6473: 
                   6474: /************ Variance of backprevalence limit ******************/
1.269     brouard  6475:  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  6476: {
                   6477:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6478:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6479: 
                   6480:   double **dnewmpar,**doldm;
                   6481:   int i, j, nhstepm, hstepm;
                   6482:   double *xp;
                   6483:   double *gp, *gm;
                   6484:   double **gradg, **trgradg;
                   6485:   double **mgm, **mgp;
                   6486:   double age,agelim;
                   6487:   int theta;
                   6488:   
                   6489:   pstamp(ficresvbl);
                   6490:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6491:   fprintf(ficresvbl,"# Age ");
                   6492:   if(nresult >=1)
                   6493:     fprintf(ficresvbl," Result# ");
                   6494:   for(i=1; i<=nlstate;i++)
                   6495:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6496:   fprintf(ficresvbl,"\n");
                   6497: 
                   6498:   xp=vector(1,npar);
                   6499:   dnewmpar=matrix(1,nlstate,1,npar);
                   6500:   doldm=matrix(1,nlstate,1,nlstate);
                   6501:   
                   6502:   hstepm=1*YEARM; /* Every year of age */
                   6503:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6504:   agelim = AGEINF;
                   6505:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6506:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6507:     if (stepm >= YEARM) hstepm=1;
                   6508:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6509:     gradg=matrix(1,npar,1,nlstate);
                   6510:     mgp=matrix(1,npar,1,nlstate);
                   6511:     mgm=matrix(1,npar,1,nlstate);
                   6512:     gp=vector(1,nlstate);
                   6513:     gm=vector(1,nlstate);
                   6514: 
                   6515:     for(theta=1; theta <=npar; theta++){
                   6516:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6517:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6518:       }
                   6519:       if(mobilavproj > 0 )
                   6520:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6521:       else
                   6522:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6523:       for(i=1;i<=nlstate;i++){
                   6524:        gp[i] = bprlim[i][i];
                   6525:        mgp[theta][i] = bprlim[i][i];
                   6526:       }
                   6527:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6528:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6529:        if(mobilavproj > 0 )
                   6530:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6531:        else
                   6532:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6533:       for(i=1;i<=nlstate;i++){
                   6534:        gm[i] = bprlim[i][i];
                   6535:        mgm[theta][i] = bprlim[i][i];
                   6536:       }
                   6537:       for(i=1;i<=nlstate;i++)
                   6538:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6539:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6540:     } /* End theta */
                   6541: 
                   6542:     trgradg =matrix(1,nlstate,1,npar);
                   6543: 
                   6544:     for(j=1; j<=nlstate;j++)
                   6545:       for(theta=1; theta <=npar; theta++)
                   6546:        trgradg[j][theta]=gradg[theta][j];
                   6547:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6548:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6549:     /*   for(j=1; j<=nlstate;j++){ */
                   6550:     /*         printf(" %d ",j); */
                   6551:     /*         for(theta=1; theta <=npar; theta++) */
                   6552:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6553:     /*         printf("\n "); */
                   6554:     /*   } */
                   6555:     /* } */
                   6556:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6557:     /*   printf("\n gradg %d ",(int)age); */
                   6558:     /*   for(j=1; j<=nlstate;j++){ */
                   6559:     /*         printf("%d ",j); */
                   6560:     /*         for(theta=1; theta <=npar; theta++) */
                   6561:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6562:     /*         printf("\n "); */
                   6563:     /*   } */
                   6564:     /* } */
                   6565: 
                   6566:     for(i=1;i<=nlstate;i++)
                   6567:       varbpl[i][(int)age] =0.;
                   6568:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6569:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6570:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6571:     }else{
                   6572:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6573:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6574:     }
                   6575:     for(i=1;i<=nlstate;i++)
                   6576:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6577: 
                   6578:     fprintf(ficresvbl,"%.0f ",age );
                   6579:     if(nresult >=1)
                   6580:       fprintf(ficresvbl,"%d ",nres );
                   6581:     for(i=1; i<=nlstate;i++)
                   6582:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6583:     fprintf(ficresvbl,"\n");
                   6584:     free_vector(gp,1,nlstate);
                   6585:     free_vector(gm,1,nlstate);
                   6586:     free_matrix(mgm,1,npar,1,nlstate);
                   6587:     free_matrix(mgp,1,npar,1,nlstate);
                   6588:     free_matrix(gradg,1,npar,1,nlstate);
                   6589:     free_matrix(trgradg,1,nlstate,1,npar);
                   6590:   } /* End age */
                   6591: 
                   6592:   free_vector(xp,1,npar);
                   6593:   free_matrix(doldm,1,nlstate,1,npar);
                   6594:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6595: 
                   6596: }
                   6597: 
                   6598: /************ Variance of one-step probabilities  ******************/
                   6599: 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  6600:  {
                   6601:    int i, j=0,  k1, l1, tj;
                   6602:    int k2, l2, j1,  z1;
                   6603:    int k=0, l;
                   6604:    int first=1, first1, first2;
                   6605:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6606:    double **dnewm,**doldm;
                   6607:    double *xp;
                   6608:    double *gp, *gm;
                   6609:    double **gradg, **trgradg;
                   6610:    double **mu;
                   6611:    double age, cov[NCOVMAX+1];
                   6612:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6613:    int theta;
                   6614:    char fileresprob[FILENAMELENGTH];
                   6615:    char fileresprobcov[FILENAMELENGTH];
                   6616:    char fileresprobcor[FILENAMELENGTH];
                   6617:    double ***varpij;
                   6618: 
                   6619:    strcpy(fileresprob,"PROB_"); 
                   6620:    strcat(fileresprob,fileres);
                   6621:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6622:      printf("Problem with resultfile: %s\n", fileresprob);
                   6623:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6624:    }
                   6625:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6626:    strcat(fileresprobcov,fileresu);
                   6627:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6628:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6629:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6630:    }
                   6631:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6632:    strcat(fileresprobcor,fileresu);
                   6633:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6634:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6635:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6636:    }
                   6637:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6638:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6639:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6640:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6641:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6642:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6643:    pstamp(ficresprob);
                   6644:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6645:    fprintf(ficresprob,"# Age");
                   6646:    pstamp(ficresprobcov);
                   6647:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6648:    fprintf(ficresprobcov,"# Age");
                   6649:    pstamp(ficresprobcor);
                   6650:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6651:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6652: 
                   6653: 
1.222     brouard  6654:    for(i=1; i<=nlstate;i++)
                   6655:      for(j=1; j<=(nlstate+ndeath);j++){
                   6656:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6657:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6658:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6659:      }  
                   6660:    /* fprintf(ficresprob,"\n");
                   6661:       fprintf(ficresprobcov,"\n");
                   6662:       fprintf(ficresprobcor,"\n");
                   6663:    */
                   6664:    xp=vector(1,npar);
                   6665:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6666:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6667:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6668:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6669:    first=1;
                   6670:    fprintf(ficgp,"\n# Routine varprob");
                   6671:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6672:    fprintf(fichtm,"\n");
                   6673: 
1.288     brouard  6674:    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  6675:    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);
                   6676:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6677: and drawn. It helps understanding how is the covariance between two incidences.\
                   6678:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6679:    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  6680: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6681: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6682: standard deviations wide on each axis. <br>\
                   6683:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6684:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6685: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6686: 
1.222     brouard  6687:    cov[1]=1;
                   6688:    /* tj=cptcoveff; */
1.225     brouard  6689:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6690:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6691:    j1=0;
1.224     brouard  6692:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6693:      if  (cptcovn>0) {
                   6694:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6695:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6696:        fprintf(ficresprob, "**********\n#\n");
                   6697:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6698:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6699:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6700:                        
1.222     brouard  6701:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6702:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6703:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6704:                        
                   6705:                        
1.222     brouard  6706:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6707:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6708:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6709:                        
1.222     brouard  6710:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6711:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6712:        fprintf(ficresprobcor, "**********\n#");    
                   6713:        if(invalidvarcomb[j1]){
                   6714:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6715:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6716:         continue;
                   6717:        }
                   6718:      }
                   6719:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6720:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6721:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6722:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6723:      for (age=bage; age<=fage; age ++){ 
                   6724:        cov[2]=age;
                   6725:        if(nagesqr==1)
                   6726:         cov[3]= age*age;
                   6727:        for (k=1; k<=cptcovn;k++) {
                   6728:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6729:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6730:                                                                    * 1  1 1 1 1
                   6731:                                                                    * 2  2 1 1 1
                   6732:                                                                    * 3  1 2 1 1
                   6733:                                                                    */
                   6734:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6735:        }
                   6736:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6737:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6738:        for (k=1; k<=cptcovprod;k++)
                   6739:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6740:                        
                   6741:                        
1.222     brouard  6742:        for(theta=1; theta <=npar; theta++){
                   6743:         for(i=1; i<=npar; i++)
                   6744:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6745:                                
1.222     brouard  6746:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6747:                                
1.222     brouard  6748:         k=0;
                   6749:         for(i=1; i<= (nlstate); i++){
                   6750:           for(j=1; j<=(nlstate+ndeath);j++){
                   6751:             k=k+1;
                   6752:             gp[k]=pmmij[i][j];
                   6753:           }
                   6754:         }
1.220     brouard  6755:                                
1.222     brouard  6756:         for(i=1; i<=npar; i++)
                   6757:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6758:                                
1.222     brouard  6759:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6760:         k=0;
                   6761:         for(i=1; i<=(nlstate); i++){
                   6762:           for(j=1; j<=(nlstate+ndeath);j++){
                   6763:             k=k+1;
                   6764:             gm[k]=pmmij[i][j];
                   6765:           }
                   6766:         }
1.220     brouard  6767:                                
1.222     brouard  6768:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6769:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6770:        }
1.126     brouard  6771: 
1.222     brouard  6772:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6773:         for(theta=1; theta <=npar; theta++)
                   6774:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6775:                        
1.222     brouard  6776:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6777:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6778:                        
1.222     brouard  6779:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6780:                        
1.222     brouard  6781:        k=0;
                   6782:        for(i=1; i<=(nlstate); i++){
                   6783:         for(j=1; j<=(nlstate+ndeath);j++){
                   6784:           k=k+1;
                   6785:           mu[k][(int) age]=pmmij[i][j];
                   6786:         }
                   6787:        }
                   6788:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6789:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6790:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6791:                        
1.222     brouard  6792:        /*printf("\n%d ",(int)age);
                   6793:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6794:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6795:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6796:         }*/
1.220     brouard  6797:                        
1.222     brouard  6798:        fprintf(ficresprob,"\n%d ",(int)age);
                   6799:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6800:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6801:                        
1.222     brouard  6802:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6803:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6804:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6805:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6806:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6807:        }
                   6808:        i=0;
                   6809:        for (k=1; k<=(nlstate);k++){
                   6810:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6811:           i++;
                   6812:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6813:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6814:           for (j=1; j<=i;j++){
                   6815:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6816:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6817:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6818:           }
                   6819:         }
                   6820:        }/* end of loop for state */
                   6821:      } /* end of loop for age */
                   6822:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6823:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6824:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6825:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6826:     
                   6827:      /* Confidence intervalle of pij  */
                   6828:      /*
                   6829:        fprintf(ficgp,"\nunset parametric;unset label");
                   6830:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6831:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6832:        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);
                   6833:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6834:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6835:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6836:      */
                   6837:                
                   6838:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6839:      first1=1;first2=2;
                   6840:      for (k2=1; k2<=(nlstate);k2++){
                   6841:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6842:         if(l2==k2) continue;
                   6843:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6844:         for (k1=1; k1<=(nlstate);k1++){
                   6845:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6846:             if(l1==k1) continue;
                   6847:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6848:             if(i<=j) continue;
                   6849:             for (age=bage; age<=fage; age ++){ 
                   6850:               if ((int)age %5==0){
                   6851:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6852:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6853:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6854:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6855:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6856:                 c12=cv12/sqrt(v1*v2);
                   6857:                 /* Computing eigen value of matrix of covariance */
                   6858:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6859:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6860:                 if ((lc2 <0) || (lc1 <0) ){
                   6861:                   if(first2==1){
                   6862:                     first1=0;
                   6863:                     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);
                   6864:                   }
                   6865:                   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);
                   6866:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6867:                   /* lc2=fabs(lc2); */
                   6868:                 }
1.220     brouard  6869:                                                                
1.222     brouard  6870:                 /* Eigen vectors */
1.280     brouard  6871:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6872:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6873:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6874:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6875:                 }else
                   6876:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6877:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6878:                 v21=(lc1-v1)/cv12*v11;
                   6879:                 v12=-v21;
                   6880:                 v22=v11;
                   6881:                 tnalp=v21/v11;
                   6882:                 if(first1==1){
                   6883:                   first1=0;
                   6884:                   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);
                   6885:                 }
                   6886:                 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);
                   6887:                 /*printf(fignu*/
                   6888:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6889:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6890:                 if(first==1){
                   6891:                   first=0;
                   6892:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6893:                   fprintf(ficgp,"\nset parametric;unset label");
                   6894:                   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);
                   6895:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6896:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6897:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6898: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6899:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6900:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6901:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6902:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6903:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6904:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6905:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6906:                   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  6907:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6908:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6909:                 }else{
                   6910:                   first=0;
                   6911:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6912:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6913:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6914:                   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  6915:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6916:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6917:                 }/* if first */
                   6918:               } /* age mod 5 */
                   6919:             } /* end loop age */
                   6920:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6921:             first=1;
                   6922:           } /*l12 */
                   6923:         } /* k12 */
                   6924:        } /*l1 */
                   6925:      }/* k1 */
                   6926:    }  /* loop on combination of covariates j1 */
                   6927:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6928:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6929:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6930:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6931:    free_vector(xp,1,npar);
                   6932:    fclose(ficresprob);
                   6933:    fclose(ficresprobcov);
                   6934:    fclose(ficresprobcor);
                   6935:    fflush(ficgp);
                   6936:    fflush(fichtmcov);
                   6937:  }
1.126     brouard  6938: 
                   6939: 
                   6940: /******************* Printing html file ***********/
1.201     brouard  6941: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6942:                  int lastpass, int stepm, int weightopt, char model[],\
                   6943:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  6944:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   6945:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   6946:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  6947:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6948: 
                   6949:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6950:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6951: </ul>");
1.237     brouard  6952:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6953: </ul>", model);
1.214     brouard  6954:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6955:    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",
                   6956:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6957:    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  6958:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6959:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6960:    fprintf(fichtm,"\
                   6961:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6962:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6963:    fprintf(fichtm,"\
1.217     brouard  6964:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6965:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6966:    fprintf(fichtm,"\
1.288     brouard  6967:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6968:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6969:    fprintf(fichtm,"\
1.288     brouard  6970:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6971:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6972:    fprintf(fichtm,"\
1.211     brouard  6973:  - (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  6974:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6975:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6976:    if(prevfcast==1){
                   6977:      fprintf(fichtm,"\
                   6978:  - Prevalence projections by age and states:                           \
1.201     brouard  6979:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6980:    }
1.126     brouard  6981: 
                   6982: 
1.225     brouard  6983:    m=pow(2,cptcoveff);
1.222     brouard  6984:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6985: 
1.264     brouard  6986:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6987: 
                   6988:    jj1=0;
                   6989: 
                   6990:    fprintf(fichtm," \n<ul>");
                   6991:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6992:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6993:      if(m != 1 && TKresult[nres]!= k1)
                   6994:        continue;
                   6995:      jj1++;
                   6996:      if (cptcovn > 0) {
                   6997:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6998:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6999:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7000:        }
                   7001:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7002:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7003:        }
                   7004:        fprintf(fichtm,"\">");
                   7005:        
                   7006:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7007:        fprintf(fichtm,"************ Results for covariates");
                   7008:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7009:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7010:        }
                   7011:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7012:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7013:        }
                   7014:        if(invalidvarcomb[k1]){
                   7015:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7016:         continue;
                   7017:        }
                   7018:        fprintf(fichtm,"</a></li>");
                   7019:      } /* cptcovn >0 */
                   7020:    }
                   7021:      fprintf(fichtm," \n</ul>");
                   7022: 
1.222     brouard  7023:    jj1=0;
1.237     brouard  7024: 
                   7025:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7026:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7027:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7028:        continue;
1.220     brouard  7029: 
1.222     brouard  7030:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7031:      jj1++;
                   7032:      if (cptcovn > 0) {
1.264     brouard  7033:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7034:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7035:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7036:        }
                   7037:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7038:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7039:        }
                   7040:        fprintf(fichtm,"\"</a>");
                   7041:  
1.222     brouard  7042:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7043:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7044:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7045:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7046:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7047:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7048:        }
1.237     brouard  7049:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7050:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7051:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7052:       }
                   7053:        
1.230     brouard  7054:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  7055:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7056:        if(invalidvarcomb[k1]){
                   7057:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7058:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7059:         continue;
                   7060:        }
                   7061:      }
                   7062:      /* aij, bij */
1.259     brouard  7063:      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  7064: <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  7065:      /* Pij */
1.241     brouard  7066:      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> \
                   7067: <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  7068:      /* Quasi-incidences */
                   7069:      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  7070:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7071:  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  7072: 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> \
                   7073: <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  7074:      /* Survival functions (period) in state j */
                   7075:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7076:        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  7077: <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  7078:      }
                   7079:      /* State specific survival functions (period) */
                   7080:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7081:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7082:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7083:  <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  7084:      }
1.288     brouard  7085:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7086:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7087:        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> \
                   7088: <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  7089:      }
1.296     brouard  7090:      if(prevbcast==1){
1.288     brouard  7091:        /* Backward prevalence in each health state */
1.222     brouard  7092:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7093:         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  7094: <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  7095:        }
1.217     brouard  7096:      }
1.222     brouard  7097:      if(prevfcast==1){
1.288     brouard  7098:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7099:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7100:         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);
                   7101:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7102:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7103:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7104:        }
                   7105:      }
1.296     brouard  7106:      if(prevbcast==1){
1.268     brouard  7107:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7108:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7109:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7110:  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 \
                   7111:  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  7112: 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);
                   7113:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7114:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7115:        }
                   7116:      }
1.220     brouard  7117:         
1.222     brouard  7118:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7119:        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);
                   7120:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7121:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7122:      }
                   7123:      /* } /\* end i1 *\/ */
                   7124:    }/* End k1 */
                   7125:    fprintf(fichtm,"</ul>");
1.126     brouard  7126: 
1.222     brouard  7127:    fprintf(fichtm,"\
1.126     brouard  7128: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7129:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7130:  - 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  7131: But because parameters are usually highly correlated (a higher incidence of disability \
                   7132: and a higher incidence of recovery can give very close observed transition) it might \
                   7133: be very useful to look not only at linear confidence intervals estimated from the \
                   7134: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7135: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7136: covariance matrix of the one-step probabilities. \
                   7137: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7138: 
1.222     brouard  7139:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7140:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7141:    fprintf(fichtm,"\
1.126     brouard  7142:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7143:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7144: 
1.222     brouard  7145:    fprintf(fichtm,"\
1.126     brouard  7146:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7147:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7148:    fprintf(fichtm,"\
1.126     brouard  7149:  - 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): \
                   7150:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7151:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7152:    fprintf(fichtm,"\
1.126     brouard  7153:  - (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): \
                   7154:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7155:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7156:    fprintf(fichtm,"\
1.288     brouard  7157:  - 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  7158:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7159:    fprintf(fichtm,"\
1.128     brouard  7160:  - 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  7161:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7162:    fprintf(fichtm,"\
1.288     brouard  7163:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7164:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7165: 
                   7166: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7167: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7168: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7169: /*     <br>",fileres,fileres,fileres,fileres); */
                   7170: /*  else  */
                   7171: /*    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  7172:    fflush(fichtm);
                   7173:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7174: 
1.225     brouard  7175:    m=pow(2,cptcoveff);
1.222     brouard  7176:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7177: 
1.222     brouard  7178:    jj1=0;
1.237     brouard  7179: 
1.241     brouard  7180:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7181:    for(k1=1; k1<=m;k1++){
1.253     brouard  7182:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7183:        continue;
1.222     brouard  7184:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7185:      jj1++;
1.126     brouard  7186:      if (cptcovn > 0) {
                   7187:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7188:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7189:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7190:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7191:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7192:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7193:       }
                   7194: 
1.126     brouard  7195:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7196: 
1.222     brouard  7197:        if(invalidvarcomb[k1]){
                   7198:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7199:         continue;
                   7200:        }
1.126     brouard  7201:      }
                   7202:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7203:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7204: 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);
                   7205:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7206:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7207:      }
                   7208:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7209: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7210: true period expectancies (those weighted with period prevalences are also\
                   7211:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7212:  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);
                   7213:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7214:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7215:      /* } /\* end i1 *\/ */
                   7216:    }/* End k1 */
1.241     brouard  7217:   }/* End nres */
1.222     brouard  7218:    fprintf(fichtm,"</ul>");
                   7219:    fflush(fichtm);
1.126     brouard  7220: }
                   7221: 
                   7222: /******************* Gnuplot file **************/
1.296     brouard  7223: 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  7224: 
                   7225:   char dirfileres[132],optfileres[132];
1.264     brouard  7226:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7227:   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  7228:   int lv=0, vlv=0, kl=0;
1.130     brouard  7229:   int ng=0;
1.201     brouard  7230:   int vpopbased;
1.223     brouard  7231:   int ioffset; /* variable offset for columns */
1.270     brouard  7232:   int iyearc=1; /* variable column for year of projection  */
                   7233:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7234:   int nres=0; /* Index of resultline */
1.266     brouard  7235:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7236: 
1.126     brouard  7237: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7238: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7239: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7240: /*   } */
                   7241: 
                   7242:   /*#ifdef windows */
                   7243:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7244:   /*#endif */
1.225     brouard  7245:   m=pow(2,cptcoveff);
1.126     brouard  7246: 
1.274     brouard  7247:   /* diagram of the model */
                   7248:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7249:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7250:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7251:   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);
                   7252: 
                   7253:   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);
                   7254:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7255:   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);
                   7256:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7257:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7258:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7259:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7260: 
1.202     brouard  7261:   /* Contribution to likelihood */
                   7262:   /* Plot the probability implied in the likelihood */
1.223     brouard  7263:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7264:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7265:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7266:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7267: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7268:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7269: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7270:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7271:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7272:   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));
                   7273:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7274:   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));
                   7275:   for (i=1; i<= nlstate ; i ++) {
                   7276:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7277:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7278:     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);
                   7279:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7280:       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);
                   7281:     }
                   7282:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7283:   }
                   7284:   /* 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 */               
                   7285:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7286:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7287:   fprintf(ficgp,"\nset out;unset log\n");
                   7288:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7289: 
1.126     brouard  7290:   strcpy(dirfileres,optionfilefiname);
                   7291:   strcpy(optfileres,"vpl");
1.223     brouard  7292:   /* 1eme*/
1.238     brouard  7293:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7294:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7295:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7296:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7297:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7298:          continue;
                   7299:        /* We are interested in selected combination by the resultline */
1.246     brouard  7300:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7301:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7302:        strcpy(gplotlabel,"(");
1.238     brouard  7303:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7304:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7305:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7306:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7307:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7308:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7309:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7310:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7311:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7312:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7313:        }
                   7314:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7315:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7316:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7317:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7318:        }
                   7319:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7320:        /* printf("\n#\n"); */
1.238     brouard  7321:        fprintf(ficgp,"\n#\n");
                   7322:        if(invalidvarcomb[k1]){
1.260     brouard  7323:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7324:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7325:          continue;
                   7326:        }
1.235     brouard  7327:       
1.241     brouard  7328:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7329:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7330:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7331:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7332:        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);
                   7333:        /* 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); */
                   7334:       /* k1-1 error should be nres-1*/
1.238     brouard  7335:        for (i=1; i<= nlstate ; i ++) {
                   7336:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7337:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7338:        }
1.288     brouard  7339:        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  7340:        for (i=1; i<= nlstate ; i ++) {
                   7341:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7342:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7343:        } 
1.260     brouard  7344:        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  7345:        for (i=1; i<= nlstate ; i ++) {
                   7346:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7347:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7348:        }  
1.265     brouard  7349:        /* 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)); */
                   7350:        
                   7351:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7352:         if(cptcoveff ==0){
1.271     brouard  7353:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7354:        }else{
                   7355:          kl=0;
                   7356:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7357:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7358:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7359:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7360:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7361:            vlv= nbcode[Tvaraff[k]][lv];
                   7362:            kl++;
                   7363:            /* 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 *\/ */
                   7364:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7365:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7366:            /* ''  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*/
                   7367:            if(k==cptcoveff){
                   7368:              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], \
                   7369:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7370:            }else{
                   7371:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7372:              kl++;
                   7373:            }
                   7374:          } /* end covariate */
                   7375:        } /* end if no covariate */
                   7376: 
1.296     brouard  7377:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7378:          /* 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  7379:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7380:          if(cptcoveff ==0){
1.245     brouard  7381:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7382:          }else{
                   7383:            kl=0;
                   7384:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7385:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7386:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7387:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7388:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7389:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7390:              kl++;
1.238     brouard  7391:              /* 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 *\/ */
                   7392:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7393:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7394:              /* ''  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*/
                   7395:              if(k==cptcoveff){
1.245     brouard  7396:                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  7397:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7398:              }else{
                   7399:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7400:                kl++;
                   7401:              }
                   7402:            } /* end covariate */
                   7403:          } /* end if no covariate */
1.296     brouard  7404:          if(prevbcast == 1){
1.268     brouard  7405:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7406:            /* k1-1 error should be nres-1*/
                   7407:            for (i=1; i<= nlstate ; i ++) {
                   7408:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7409:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7410:            }
1.271     brouard  7411:            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  7412:            for (i=1; i<= nlstate ; i ++) {
                   7413:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7414:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7415:            } 
1.276     brouard  7416:            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  7417:            for (i=1; i<= nlstate ; i ++) {
                   7418:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7419:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7420:            } 
1.274     brouard  7421:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7422:          } /* end if backprojcast */
1.296     brouard  7423:        } /* end if prevbcast */
1.276     brouard  7424:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7425:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7426:       } /* nres */
1.201     brouard  7427:     } /* k1 */
                   7428:   } /* cpt */
1.235     brouard  7429: 
                   7430:   
1.126     brouard  7431:   /*2 eme*/
1.238     brouard  7432:   for (k1=1; k1<= m ; k1 ++){  
                   7433:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7434:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7435:        continue;
                   7436:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7437:       strcpy(gplotlabel,"(");
1.238     brouard  7438:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7439:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7440:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7441:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7442:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7443:        vlv= nbcode[Tvaraff[k]][lv];
                   7444:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7445:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7446:       }
1.237     brouard  7447:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7448:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7449:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7450:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7451:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7452:       }
1.264     brouard  7453:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7454:       fprintf(ficgp,"\n#\n");
1.223     brouard  7455:       if(invalidvarcomb[k1]){
                   7456:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7457:        continue;
                   7458:       }
1.219     brouard  7459:                        
1.241     brouard  7460:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7461:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7462:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7463:        if(vpopbased==0){
1.238     brouard  7464:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7465:        }else
1.238     brouard  7466:          fprintf(ficgp,"\nreplot ");
                   7467:        for (i=1; i<= nlstate+1 ; i ++) {
                   7468:          k=2*i;
1.261     brouard  7469:          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  7470:          for (j=1; j<= nlstate+1 ; j ++) {
                   7471:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7472:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7473:          }   
                   7474:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7475:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7476:          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  7477:          for (j=1; j<= nlstate+1 ; j ++) {
                   7478:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7479:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7480:          }   
                   7481:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7482:          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  7483:          for (j=1; j<= nlstate+1 ; j ++) {
                   7484:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7485:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7486:          }   
                   7487:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7488:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7489:        } /* state */
                   7490:       } /* vpopbased */
1.264     brouard  7491:       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  7492:     } /* end nres */
                   7493:   } /* k1 end 2 eme*/
                   7494:        
                   7495:        
                   7496:   /*3eme*/
                   7497:   for (k1=1; k1<= m ; k1 ++){
                   7498:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7499:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7500:        continue;
                   7501: 
                   7502:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7503:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7504:        strcpy(gplotlabel,"(");
1.238     brouard  7505:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7506:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7507:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7508:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7509:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7510:          vlv= nbcode[Tvaraff[k]][lv];
                   7511:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7512:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7513:        }
                   7514:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7515:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7516:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7517:        }       
1.264     brouard  7518:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7519:        fprintf(ficgp,"\n#\n");
                   7520:        if(invalidvarcomb[k1]){
                   7521:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7522:          continue;
                   7523:        }
                   7524:                        
                   7525:        /*       k=2+nlstate*(2*cpt-2); */
                   7526:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7527:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7528:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7529:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7530: 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  7531:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7532:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7533:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7534:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7535:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7536:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7537:                                
1.238     brouard  7538:        */
                   7539:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7540:          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  7541:          /*    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  7542:                                
1.238     brouard  7543:        } 
1.261     brouard  7544:        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  7545:       }
1.264     brouard  7546:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7547:     } /* end nres */
                   7548:   } /* end kl 3eme */
1.126     brouard  7549:   
1.223     brouard  7550:   /* 4eme */
1.201     brouard  7551:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7552:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7553:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7554:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7555:        continue;
1.238     brouard  7556:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7557:        strcpy(gplotlabel,"(");
1.238     brouard  7558:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7559:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7560:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7561:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7562:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7563:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7564:          vlv= nbcode[Tvaraff[k]][lv];
                   7565:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7566:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7567:        }
                   7568:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7569:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7570:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7571:        }       
1.264     brouard  7572:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7573:        fprintf(ficgp,"\n#\n");
                   7574:        if(invalidvarcomb[k1]){
                   7575:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7576:          continue;
1.223     brouard  7577:        }
1.238     brouard  7578:       
1.241     brouard  7579:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7580:        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  7581:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7582: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7583:        k=3;
                   7584:        for (i=1; i<= nlstate ; i ++){
                   7585:          if(i==1){
                   7586:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7587:          }else{
                   7588:            fprintf(ficgp,", '' ");
                   7589:          }
                   7590:          l=(nlstate+ndeath)*(i-1)+1;
                   7591:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7592:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7593:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7594:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7595:        } /* nlstate */
1.264     brouard  7596:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7597:       } /* end cpt state*/ 
                   7598:     } /* end nres */
                   7599:   } /* end covariate k1 */  
                   7600: 
1.220     brouard  7601: /* 5eme */
1.201     brouard  7602:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7603:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7604:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7605:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7606:        continue;
1.238     brouard  7607:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7608:        strcpy(gplotlabel,"(");
1.238     brouard  7609:        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);
                   7610:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7611:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7612:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7613:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7614:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7615:          vlv= nbcode[Tvaraff[k]][lv];
                   7616:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7617:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7618:        }
                   7619:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7620:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7621:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7622:        }       
1.264     brouard  7623:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7624:        fprintf(ficgp,"\n#\n");
                   7625:        if(invalidvarcomb[k1]){
                   7626:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7627:          continue;
                   7628:        }
1.227     brouard  7629:       
1.241     brouard  7630:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7631:        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  7632:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7633: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7634:        k=3;
                   7635:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7636:          if(j==1)
                   7637:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7638:          else
                   7639:            fprintf(ficgp,", '' ");
                   7640:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7641:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7642:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7643:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7644:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7645:        } /* nlstate */
                   7646:        fprintf(ficgp,", '' ");
                   7647:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7648:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7649:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7650:          if(j < nlstate)
                   7651:            fprintf(ficgp,"$%d +",k+l);
                   7652:          else
                   7653:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7654:        }
1.264     brouard  7655:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7656:       } /* end cpt state*/ 
                   7657:     } /* end covariate */  
                   7658:   } /* end nres */
1.227     brouard  7659:   
1.220     brouard  7660: /* 6eme */
1.202     brouard  7661:   /* CV preval stable (period) for each covariate */
1.237     brouard  7662:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7663:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7664:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7665:       continue;
1.255     brouard  7666:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7667:       strcpy(gplotlabel,"(");      
1.288     brouard  7668:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7669:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7670:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7671:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7672:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7673:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7674:        vlv= nbcode[Tvaraff[k]][lv];
                   7675:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7676:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7677:       }
1.237     brouard  7678:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7679:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7680:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7681:       }        
1.264     brouard  7682:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7683:       fprintf(ficgp,"\n#\n");
1.223     brouard  7684:       if(invalidvarcomb[k1]){
1.227     brouard  7685:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7686:        continue;
1.223     brouard  7687:       }
1.227     brouard  7688:       
1.241     brouard  7689:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7690:       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  7691:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7692: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7693:       k=3; /* Offset */
1.255     brouard  7694:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7695:        if(i==1)
                   7696:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7697:        else
                   7698:          fprintf(ficgp,", '' ");
1.255     brouard  7699:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7700:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7701:        for (j=2; j<= nlstate ; j ++)
                   7702:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7703:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7704:       } /* nlstate */
1.264     brouard  7705:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7706:     } /* end cpt state*/ 
                   7707:   } /* end covariate */  
1.227     brouard  7708:   
                   7709:   
1.220     brouard  7710: /* 7eme */
1.296     brouard  7711:   if(prevbcast == 1){
1.288     brouard  7712:     /* CV backward prevalence  for each covariate */
1.237     brouard  7713:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7714:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7715:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7716:        continue;
1.268     brouard  7717:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7718:        strcpy(gplotlabel,"(");      
1.288     brouard  7719:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7720:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7721:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7722:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7723:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7724:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7725:          vlv= nbcode[Tvaraff[k]][lv];
                   7726:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7727:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7728:        }
1.237     brouard  7729:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7730:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7731:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7732:        }       
1.264     brouard  7733:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7734:        fprintf(ficgp,"\n#\n");
                   7735:        if(invalidvarcomb[k1]){
                   7736:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7737:          continue;
                   7738:        }
                   7739:        
1.241     brouard  7740:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7741:        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  7742:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7743: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7744:        k=3; /* Offset */
1.268     brouard  7745:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7746:          if(i==1)
                   7747:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7748:          else
                   7749:            fprintf(ficgp,", '' ");
                   7750:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7751:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7752:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7753:          /* 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  7754:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7755:          /* for (j=2; j<= nlstate ; j ++) */
                   7756:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7757:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7758:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7759:        } /* nlstate */
1.264     brouard  7760:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7761:       } /* end cpt state*/ 
                   7762:     } /* end covariate */  
1.296     brouard  7763:   } /* End if prevbcast */
1.218     brouard  7764:   
1.223     brouard  7765:   /* 8eme */
1.218     brouard  7766:   if(prevfcast==1){
1.288     brouard  7767:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7768:     
1.237     brouard  7769:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7770:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7771:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7772:        continue;
1.211     brouard  7773:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7774:        strcpy(gplotlabel,"(");      
1.288     brouard  7775:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7776:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7777:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7778:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7779:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7780:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7781:          vlv= nbcode[Tvaraff[k]][lv];
                   7782:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7783:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7784:        }
1.237     brouard  7785:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7786:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7787:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7788:        }       
1.264     brouard  7789:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7790:        fprintf(ficgp,"\n#\n");
                   7791:        if(invalidvarcomb[k1]){
                   7792:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7793:          continue;
                   7794:        }
                   7795:        
                   7796:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7797:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7798:        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  7799:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7800: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7801: 
                   7802:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7803:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7804:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7805:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7806:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7807:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7808:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7809:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7810:          if(i==istart){
1.227     brouard  7811:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7812:          }else{
                   7813:            fprintf(ficgp,",\\\n '' ");
                   7814:          }
                   7815:          if(cptcoveff ==0){ /* No covariate */
                   7816:            ioffset=2; /* Age is in 2 */
                   7817:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7818:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7819:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7820:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7821:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7822:            if(i==nlstate+1){
1.270     brouard  7823:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7824:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7825:              fprintf(ficgp,",\\\n '' ");
                   7826:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7827:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7828:                     offyear,                           \
1.268     brouard  7829:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7830:            }else
1.227     brouard  7831:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7832:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7833:          }else{ /* more than 2 covariates */
1.270     brouard  7834:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7835:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7836:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7837:            iyearc=ioffset-1;
                   7838:            iagec=ioffset;
1.227     brouard  7839:            fprintf(ficgp," u %d:(",ioffset); 
                   7840:            kl=0;
                   7841:            strcpy(gplotcondition,"(");
                   7842:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7843:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7844:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7845:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7846:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7847:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7848:              kl++;
                   7849:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7850:              kl++;
                   7851:              if(k <cptcoveff && cptcoveff>1)
                   7852:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7853:            }
                   7854:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7855:            /* 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 *\/ */
                   7856:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7857:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7858:            /* ''  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*/
                   7859:            if(i==nlstate+1){
1.270     brouard  7860:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7861:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7862:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7863:              fprintf(ficgp," u %d:(",iagec); 
                   7864:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7865:                      iyearc, iagec, offyear,                           \
                   7866:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7867: /*  '' 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  7868:            }else{
                   7869:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7870:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7871:            }
                   7872:          } /* end if covariate */
                   7873:        } /* nlstate */
1.264     brouard  7874:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7875:       } /* end cpt state*/
                   7876:     } /* end covariate */
                   7877:   } /* End if prevfcast */
1.227     brouard  7878:   
1.296     brouard  7879:   if(prevbcast==1){
1.268     brouard  7880:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7881:     
                   7882:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7883:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7884:       if(m != 1 && TKresult[nres]!= k1)
                   7885:        continue;
                   7886:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7887:        strcpy(gplotlabel,"(");      
                   7888:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7889:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7890:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7891:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7892:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7893:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7894:          vlv= nbcode[Tvaraff[k]][lv];
                   7895:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7896:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7897:        }
                   7898:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7899:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7900:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7901:        }       
                   7902:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7903:        fprintf(ficgp,"\n#\n");
                   7904:        if(invalidvarcomb[k1]){
                   7905:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7906:          continue;
                   7907:        }
                   7908:        
                   7909:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7910:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7911:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7912:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7913: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7914: 
                   7915:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7916:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7917:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7918:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7919:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7920:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7921:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7922:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7923:          if(i==istart){
                   7924:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7925:          }else{
                   7926:            fprintf(ficgp,",\\\n '' ");
                   7927:          }
                   7928:          if(cptcoveff ==0){ /* No covariate */
                   7929:            ioffset=2; /* Age is in 2 */
                   7930:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7931:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7932:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7933:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7934:            fprintf(ficgp," u %d:(", ioffset); 
                   7935:            if(i==nlstate+1){
1.270     brouard  7936:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7937:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7938:              fprintf(ficgp,",\\\n '' ");
                   7939:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7940:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7941:                     offbyear,                          \
                   7942:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7943:            }else
                   7944:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7945:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7946:          }else{ /* more than 2 covariates */
1.270     brouard  7947:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7948:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7949:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7950:            iyearc=ioffset-1;
                   7951:            iagec=ioffset;
1.268     brouard  7952:            fprintf(ficgp," u %d:(",ioffset); 
                   7953:            kl=0;
                   7954:            strcpy(gplotcondition,"(");
                   7955:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7956:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   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 */
                   7959:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7960:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7961:              kl++;
                   7962:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7963:              kl++;
                   7964:              if(k <cptcoveff && cptcoveff>1)
                   7965:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7966:            }
                   7967:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7968:            /* 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 *\/ */
                   7969:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7970:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7971:            /* ''  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*/
                   7972:            if(i==nlstate+1){
1.270     brouard  7973:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7974:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7975:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7976:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7977:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7978:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7979:                      iyearc,iagec,offbyear,                            \
                   7980:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7981: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7982:            }else{
                   7983:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7984:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7985:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7986:            }
                   7987:          } /* end if covariate */
                   7988:        } /* nlstate */
                   7989:        fprintf(ficgp,"\nset out; unset label;\n");
                   7990:       } /* end cpt state*/
                   7991:     } /* end covariate */
1.296     brouard  7992:   } /* End if prevbcast */
1.268     brouard  7993:   
1.227     brouard  7994:   
1.238     brouard  7995:   /* 9eme writing MLE parameters */
                   7996:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7997:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7998:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7999:     for(k=1; k <=(nlstate+ndeath); k++){
                   8000:       if (k != i) {
1.227     brouard  8001:        fprintf(ficgp,"#   current state %d\n",k);
                   8002:        for(j=1; j <=ncovmodel; j++){
                   8003:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8004:          jk++; 
                   8005:        }
                   8006:        fprintf(ficgp,"\n");
1.126     brouard  8007:       }
                   8008:     }
1.223     brouard  8009:   }
1.187     brouard  8010:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8011:   
1.145     brouard  8012:   /*goto avoid;*/
1.238     brouard  8013:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8014:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8015:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8016:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8017:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8018:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8019:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8020:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8021:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8022:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8023:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8024:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8025:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8026:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8027:   fprintf(ficgp,"#\n");
1.223     brouard  8028:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8029:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8030:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8031:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8032:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8033:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8034:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8035:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8036:        continue;
1.264     brouard  8037:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8038:       strcpy(gplotlabel,"(");
1.276     brouard  8039:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8040:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8041:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8042:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8043:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8044:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8045:        vlv= nbcode[Tvaraff[k]][lv];
                   8046:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8047:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8048:       }
1.237     brouard  8049:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8050:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8051:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8052:       }        
1.264     brouard  8053:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8054:       fprintf(ficgp,"\n#\n");
1.264     brouard  8055:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8056:       fprintf(ficgp,"\nset key outside ");
                   8057:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8058:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8059:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8060:       if (ng==1){
                   8061:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8062:        fprintf(ficgp,"\nunset log y");
                   8063:       }else if (ng==2){
                   8064:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8065:        fprintf(ficgp,"\nset log y");
                   8066:       }else if (ng==3){
                   8067:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8068:        fprintf(ficgp,"\nset log y");
                   8069:       }else
                   8070:        fprintf(ficgp,"\nunset title ");
                   8071:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8072:       i=1;
                   8073:       for(k2=1; k2<=nlstate; k2++) {
                   8074:        k3=i;
                   8075:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8076:          if (k != k2){
                   8077:            switch( ng) {
                   8078:            case 1:
                   8079:              if(nagesqr==0)
                   8080:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8081:              else /* nagesqr =1 */
                   8082:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8083:              break;
                   8084:            case 2: /* ng=2 */
                   8085:              if(nagesqr==0)
                   8086:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8087:              else /* nagesqr =1 */
                   8088:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8089:              break;
                   8090:            case 3:
                   8091:              if(nagesqr==0)
                   8092:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8093:              else /* nagesqr =1 */
                   8094:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8095:              break;
                   8096:            }
                   8097:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8098:            ijp=1; /* product no age */
                   8099:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8100:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8101:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8102:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8103:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8104:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8105:                    if(DummyV[j]==0){
                   8106:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8107:                    }else{ /* quantitative */
                   8108:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8109:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8110:                    }
                   8111:                    ij++;
1.237     brouard  8112:                  }
1.268     brouard  8113:                } 
                   8114:              }else if(cptcovprod >0){
                   8115:                if(j==Tprod[ijp]) { /* */ 
                   8116:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8117:                  if(ijp <=cptcovprod) { /* Product */
                   8118:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8119:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8120:                        /* 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)]); */
                   8121:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8122:                      }else{ /* Vn is dummy and Vm is quanti */
                   8123:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8124:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8125:                      }
                   8126:                    }else{ /* Vn*Vm Vn is quanti */
                   8127:                      if(DummyV[Tvard[ijp][2]]==0){
                   8128:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8129:                      }else{ /* Both quanti */
                   8130:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8131:                      }
1.237     brouard  8132:                    }
1.268     brouard  8133:                    ijp++;
1.237     brouard  8134:                  }
1.268     brouard  8135:                } /* end Tprod */
1.237     brouard  8136:              } else{  /* simple covariate */
1.264     brouard  8137:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8138:                if(Dummy[j]==0){
                   8139:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8140:                }else{ /* quantitative */
                   8141:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8142:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8143:                }
1.237     brouard  8144:              } /* end simple */
                   8145:            } /* end j */
1.223     brouard  8146:          }else{
                   8147:            i=i-ncovmodel;
                   8148:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8149:              fprintf(ficgp," (1.");
                   8150:          }
1.227     brouard  8151:          
1.223     brouard  8152:          if(ng != 1){
                   8153:            fprintf(ficgp,")/(1");
1.227     brouard  8154:            
1.264     brouard  8155:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8156:              if(nagesqr==0)
1.264     brouard  8157:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8158:              else /* nagesqr =1 */
1.264     brouard  8159:                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  8160:               
1.223     brouard  8161:              ij=1;
                   8162:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8163:                 if(cptcovage >0){ 
                   8164:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8165:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8166:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8167:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8168:                       ij++;
                   8169:                     }
                   8170:                   }
                   8171:                 }else
                   8172:                   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  8173:              }
                   8174:              fprintf(ficgp,")");
                   8175:            }
                   8176:            fprintf(ficgp,")");
                   8177:            if(ng ==2)
1.276     brouard  8178:              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  8179:            else /* ng= 3 */
1.276     brouard  8180:              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  8181:          }else{ /* end ng <> 1 */
                   8182:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8183:              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  8184:          }
                   8185:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8186:            fprintf(ficgp,",");
                   8187:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8188:            fprintf(ficgp,",");
                   8189:          i=i+ncovmodel;
                   8190:        } /* end k */
                   8191:       } /* end k2 */
1.276     brouard  8192:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8193:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8194:     } /* end k1 */
1.223     brouard  8195:   } /* end ng */
                   8196:   /* avoid: */
                   8197:   fflush(ficgp); 
1.126     brouard  8198: }  /* end gnuplot */
                   8199: 
                   8200: 
                   8201: /*************** Moving average **************/
1.219     brouard  8202: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8203:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8204:    
1.222     brouard  8205:    int i, cpt, cptcod;
                   8206:    int modcovmax =1;
                   8207:    int mobilavrange, mob;
                   8208:    int iage=0;
1.288     brouard  8209:    int firstA1=0, firstA2=0;
1.222     brouard  8210: 
1.266     brouard  8211:    double sum=0., sumr=0.;
1.222     brouard  8212:    double age;
1.266     brouard  8213:    double *sumnewp, *sumnewm, *sumnewmr;
                   8214:    double *agemingood, *agemaxgood; 
                   8215:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8216:   
                   8217:   
1.278     brouard  8218:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8219:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8220: 
                   8221:    sumnewp = vector(1,ncovcombmax);
                   8222:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8223:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8224:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8225:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8226:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8227:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8228: 
                   8229:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8230:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8231:      sumnewp[cptcod]=0.;
1.266     brouard  8232:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8233:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8234:    }
                   8235:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8236:   
1.266     brouard  8237:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8238:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8239:      else mobilavrange=mobilav;
                   8240:      for (age=bage; age<=fage; age++)
                   8241:        for (i=1; i<=nlstate;i++)
                   8242:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8243:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8244:      /* We keep the original values on the extreme ages bage, fage and for 
                   8245:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8246:        we use a 5 terms etc. until the borders are no more concerned. 
                   8247:      */ 
                   8248:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8249:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8250:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8251:           sumnewm[cptcod]=0.;
                   8252:           for (i=1; i<=nlstate;i++){
1.222     brouard  8253:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8254:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8255:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8256:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8257:             }
                   8258:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8259:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8260:           } /* end i */
                   8261:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8262:         } /* end cptcod */
1.222     brouard  8263:        }/* end age */
                   8264:      }/* end mob */
1.266     brouard  8265:    }else{
                   8266:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8267:      return -1;
1.266     brouard  8268:    }
                   8269: 
                   8270:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8271:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8272:      if(invalidvarcomb[cptcod]){
                   8273:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8274:        continue;
                   8275:      }
1.219     brouard  8276: 
1.266     brouard  8277:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8278:        sumnewm[cptcod]=0.;
                   8279:        sumnewmr[cptcod]=0.;
                   8280:        for (i=1; i<=nlstate;i++){
                   8281:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8282:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8283:        }
                   8284:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8285:         agemingoodr[cptcod]=age;
                   8286:        }
                   8287:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8288:           agemingood[cptcod]=age;
                   8289:        }
                   8290:      } /* age */
                   8291:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8292:        sumnewm[cptcod]=0.;
1.266     brouard  8293:        sumnewmr[cptcod]=0.;
1.222     brouard  8294:        for (i=1; i<=nlstate;i++){
                   8295:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8296:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8297:        }
                   8298:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8299:         agemaxgoodr[cptcod]=age;
1.222     brouard  8300:        }
                   8301:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8302:         agemaxgood[cptcod]=age;
                   8303:        }
                   8304:      } /* age */
                   8305:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8306:      /* but they will change */
1.288     brouard  8307:      firstA1=0;firstA2=0;
1.266     brouard  8308:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8309:        sumnewm[cptcod]=0.;
                   8310:        sumnewmr[cptcod]=0.;
                   8311:        for (i=1; i<=nlstate;i++){
                   8312:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8313:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8314:        }
                   8315:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8316:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8317:           agemaxgoodr[cptcod]=age;  /* age min */
                   8318:           for (i=1; i<=nlstate;i++)
                   8319:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8320:         }else{ /* bad we change the value with the values of good ages */
                   8321:           for (i=1; i<=nlstate;i++){
                   8322:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8323:           } /* i */
                   8324:         } /* end bad */
                   8325:        }else{
                   8326:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8327:           agemaxgood[cptcod]=age;
                   8328:         }else{ /* bad we change the value with the values of good ages */
                   8329:           for (i=1; i<=nlstate;i++){
                   8330:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8331:           } /* i */
                   8332:         } /* end bad */
                   8333:        }/* end else */
                   8334:        sum=0.;sumr=0.;
                   8335:        for (i=1; i<=nlstate;i++){
                   8336:         sum+=mobaverage[(int)age][i][cptcod];
                   8337:         sumr+=probs[(int)age][i][cptcod];
                   8338:        }
                   8339:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8340:         if(!firstA1){
                   8341:           firstA1=1;
                   8342:           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);
                   8343:         }
                   8344:         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  8345:        } /* end bad */
                   8346:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8347:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8348:         if(!firstA2){
                   8349:           firstA2=1;
                   8350:           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);
                   8351:         }
                   8352:         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  8353:        } /* end bad */
                   8354:      }/* age */
1.266     brouard  8355: 
                   8356:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8357:        sumnewm[cptcod]=0.;
1.266     brouard  8358:        sumnewmr[cptcod]=0.;
1.222     brouard  8359:        for (i=1; i<=nlstate;i++){
                   8360:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8361:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8362:        } 
                   8363:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8364:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8365:           agemingoodr[cptcod]=age;
                   8366:           for (i=1; i<=nlstate;i++)
                   8367:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8368:         }else{ /* bad we change the value with the values of good ages */
                   8369:           for (i=1; i<=nlstate;i++){
                   8370:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8371:           } /* i */
                   8372:         } /* end bad */
                   8373:        }else{
                   8374:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8375:           agemingood[cptcod]=age;
                   8376:         }else{ /* bad */
                   8377:           for (i=1; i<=nlstate;i++){
                   8378:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8379:           } /* i */
                   8380:         } /* end bad */
                   8381:        }/* end else */
                   8382:        sum=0.;sumr=0.;
                   8383:        for (i=1; i<=nlstate;i++){
                   8384:         sum+=mobaverage[(int)age][i][cptcod];
                   8385:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8386:        }
1.266     brouard  8387:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8388:         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  8389:        } /* end bad */
                   8390:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8391:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8392:         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  8393:        } /* end bad */
                   8394:      }/* age */
1.266     brouard  8395: 
1.222     brouard  8396:                
                   8397:      for (age=bage; age<=fage; age++){
1.235     brouard  8398:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8399:        sumnewp[cptcod]=0.;
                   8400:        sumnewm[cptcod]=0.;
                   8401:        for (i=1; i<=nlstate;i++){
                   8402:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8403:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8404:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8405:        }
                   8406:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8407:      }
                   8408:      /* printf("\n"); */
                   8409:      /* } */
1.266     brouard  8410: 
1.222     brouard  8411:      /* brutal averaging */
1.266     brouard  8412:      /* for (i=1; i<=nlstate;i++){ */
                   8413:      /*   for (age=1; age<=bage; age++){ */
                   8414:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8415:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8416:      /*   }     */
                   8417:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8418:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8419:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8420:      /*   } */
                   8421:      /* } /\* end i status *\/ */
                   8422:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8423:      /*   for (age=1; age<=AGESUP; age++){ */
                   8424:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8425:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8426:      /*   } */
                   8427:      /* } */
1.222     brouard  8428:    }/* end cptcod */
1.266     brouard  8429:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8430:    free_vector(agemaxgood,1, ncovcombmax);
                   8431:    free_vector(agemingood,1, ncovcombmax);
                   8432:    free_vector(agemingoodr,1, ncovcombmax);
                   8433:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8434:    free_vector(sumnewm,1, ncovcombmax);
                   8435:    free_vector(sumnewp,1, ncovcombmax);
                   8436:    return 0;
                   8437:  }/* End movingaverage */
1.218     brouard  8438:  
1.126     brouard  8439: 
1.296     brouard  8440:  
1.126     brouard  8441: /************** Forecasting ******************/
1.296     brouard  8442: /* 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)*/
                   8443: 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){
                   8444:   /* dateintemean, mean date of interviews
                   8445:      dateprojd, year, month, day of starting projection 
                   8446:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8447:      agemin, agemax range of age
                   8448:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8449:   */
1.296     brouard  8450:   /* double anprojd, mprojd, jprojd; */
                   8451:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8452:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8453:   double agec; /* generic age */
1.296     brouard  8454:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8455:   double *popeffectif,*popcount;
                   8456:   double ***p3mat;
1.218     brouard  8457:   /* double ***mobaverage; */
1.126     brouard  8458:   char fileresf[FILENAMELENGTH];
                   8459: 
                   8460:   agelim=AGESUP;
1.211     brouard  8461:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8462:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8463:      We still use firstpass and lastpass as another selection.
                   8464:   */
1.214     brouard  8465:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8466:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8467:  
1.201     brouard  8468:   strcpy(fileresf,"F_"); 
                   8469:   strcat(fileresf,fileresu);
1.126     brouard  8470:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8471:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8472:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8473:   }
1.235     brouard  8474:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8475:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8476: 
1.225     brouard  8477:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8478: 
                   8479: 
                   8480:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8481:   if (stepm<=12) stepsize=1;
                   8482:   if(estepm < stepm){
                   8483:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8484:   }
1.270     brouard  8485:   else{
                   8486:     hstepm=estepm;   
                   8487:   }
                   8488:   if(estepm > stepm){ /* Yes every two year */
                   8489:     stepsize=2;
                   8490:   }
1.296     brouard  8491:   hstepm=hstepm/stepm;
1.126     brouard  8492: 
1.296     brouard  8493:   
                   8494:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8495:   /*                              fractional in yp1 *\/ */
                   8496:   /* aintmean=yp; */
                   8497:   /* yp2=modf((yp1*12),&yp); */
                   8498:   /* mintmean=yp; */
                   8499:   /* yp1=modf((yp2*30.5),&yp); */
                   8500:   /* jintmean=yp; */
                   8501:   /* if(jintmean==0) jintmean=1; */
                   8502:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8503: 
1.296     brouard  8504: 
                   8505:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8506:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8507:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8508:   i1=pow(2,cptcoveff);
1.126     brouard  8509:   if (cptcovn < 1){i1=1;}
                   8510:   
1.296     brouard  8511:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8512:   
                   8513:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8514:   
1.126     brouard  8515: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8516:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8517:   for(k=1; k<=i1;k++){
1.253     brouard  8518:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8519:       continue;
1.227     brouard  8520:     if(invalidvarcomb[k]){
                   8521:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8522:       continue;
                   8523:     }
                   8524:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8525:     for(j=1;j<=cptcoveff;j++) {
                   8526:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8527:     }
1.235     brouard  8528:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8529:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8530:     }
1.227     brouard  8531:     fprintf(ficresf," yearproj age");
                   8532:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8533:       for(i=1; i<=nlstate;i++)               
                   8534:        fprintf(ficresf," p%d%d",i,j);
                   8535:       fprintf(ficresf," wp.%d",j);
                   8536:     }
1.296     brouard  8537:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8538:       fprintf(ficresf,"\n");
1.296     brouard  8539:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8540:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8541:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8542:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8543:        nhstepm = nhstepm/hstepm; 
                   8544:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8545:        oldm=oldms;savm=savms;
1.268     brouard  8546:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8547:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8548:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8549:        for (h=0; h<=nhstepm; h++){
                   8550:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8551:            break;
                   8552:          }
                   8553:        }
                   8554:        fprintf(ficresf,"\n");
                   8555:        for(j=1;j<=cptcoveff;j++) 
                   8556:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8557:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8558:        
                   8559:        for(j=1; j<=nlstate+ndeath;j++) {
                   8560:          ppij=0.;
                   8561:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8562:            if (mobilav>=1)
                   8563:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8564:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8565:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8566:            }
1.268     brouard  8567:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8568:          } /* end i */
                   8569:          fprintf(ficresf," %.3f", ppij);
                   8570:        }/* end j */
1.227     brouard  8571:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8572:       } /* end agec */
1.266     brouard  8573:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8574:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8575:     } /* end yearp */
                   8576:   } /* end  k */
1.219     brouard  8577:        
1.126     brouard  8578:   fclose(ficresf);
1.215     brouard  8579:   printf("End of Computing forecasting \n");
                   8580:   fprintf(ficlog,"End of Computing forecasting\n");
                   8581: 
1.126     brouard  8582: }
                   8583: 
1.269     brouard  8584: /************** Back Forecasting ******************/
1.296     brouard  8585:  /* 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){ */
                   8586:  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){
                   8587:   /* back1, year, month, day of starting backprojection
1.267     brouard  8588:      agemin, agemax range of age
                   8589:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8590:      anback2 year of end of backprojection (same day and month as back1).
                   8591:      prevacurrent and prev are prevalences.
1.267     brouard  8592:   */
                   8593:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8594:   double agec; /* generic age */
1.302     brouard  8595:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8596:   double *popeffectif,*popcount;
                   8597:   double ***p3mat;
                   8598:   /* double ***mobaverage; */
                   8599:   char fileresfb[FILENAMELENGTH];
                   8600:  
1.268     brouard  8601:   agelim=AGEINF;
1.267     brouard  8602:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8603:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8604:      We still use firstpass and lastpass as another selection.
                   8605:   */
                   8606:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8607:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8608: 
                   8609:   /*Do we need to compute prevalence again?*/
                   8610: 
                   8611:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8612:   
                   8613:   strcpy(fileresfb,"FB_");
                   8614:   strcat(fileresfb,fileresu);
                   8615:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8616:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8617:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8618:   }
                   8619:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8620:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8621:   
                   8622:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8623:   
                   8624:    
                   8625:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8626:   if (stepm<=12) stepsize=1;
                   8627:   if(estepm < stepm){
                   8628:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8629:   }
1.270     brouard  8630:   else{
                   8631:     hstepm=estepm;   
                   8632:   }
                   8633:   if(estepm >= stepm){ /* Yes every two year */
                   8634:     stepsize=2;
                   8635:   }
1.267     brouard  8636:   
                   8637:   hstepm=hstepm/stepm;
1.296     brouard  8638:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8639:   /*                              fractional in yp1 *\/ */
                   8640:   /* aintmean=yp; */
                   8641:   /* yp2=modf((yp1*12),&yp); */
                   8642:   /* mintmean=yp; */
                   8643:   /* yp1=modf((yp2*30.5),&yp); */
                   8644:   /* jintmean=yp; */
                   8645:   /* if(jintmean==0) jintmean=1; */
                   8646:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8647:   
                   8648:   i1=pow(2,cptcoveff);
                   8649:   if (cptcovn < 1){i1=1;}
                   8650:   
1.296     brouard  8651:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8652:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8653:   
                   8654:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8655:   
                   8656:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8657:   for(k=1; k<=i1;k++){
                   8658:     if(i1 != 1 && TKresult[nres]!= k)
                   8659:       continue;
                   8660:     if(invalidvarcomb[k]){
                   8661:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8662:       continue;
                   8663:     }
1.268     brouard  8664:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8665:     for(j=1;j<=cptcoveff;j++) {
                   8666:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8667:     }
                   8668:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8669:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8670:     }
                   8671:     fprintf(ficresfb," yearbproj age");
                   8672:     for(j=1; j<=nlstate+ndeath;j++){
                   8673:       for(i=1; i<=nlstate;i++)
1.268     brouard  8674:        fprintf(ficresfb," b%d%d",i,j);
                   8675:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8676:     }
1.296     brouard  8677:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8678:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8679:       fprintf(ficresfb,"\n");
1.296     brouard  8680:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8681:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8682:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8683:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8684:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8685:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8686:        nhstepm = nhstepm/hstepm;
                   8687:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8688:        oldm=oldms;savm=savms;
1.268     brouard  8689:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8690:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8691:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8692:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8693:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8694:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8695:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8696:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8697:            break;
                   8698:          }
                   8699:        }
                   8700:        fprintf(ficresfb,"\n");
                   8701:        for(j=1;j<=cptcoveff;j++)
                   8702:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8703:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8704:        for(i=1; i<=nlstate+ndeath;i++) {
                   8705:          ppij=0.;ppi=0.;
                   8706:          for(j=1; j<=nlstate;j++) {
                   8707:            /* if (mobilav==1) */
1.269     brouard  8708:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8709:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8710:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8711:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8712:              /* else { */
                   8713:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8714:              /* } */
1.268     brouard  8715:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8716:          } /* end j */
                   8717:          if(ppi <0.99){
                   8718:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8719:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8720:          }
                   8721:          fprintf(ficresfb," %.3f", ppij);
                   8722:        }/* end j */
1.267     brouard  8723:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8724:       } /* end agec */
                   8725:     } /* end yearp */
                   8726:   } /* end k */
1.217     brouard  8727:   
1.267     brouard  8728:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8729:   
1.267     brouard  8730:   fclose(ficresfb);
                   8731:   printf("End of Computing Back forecasting \n");
                   8732:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8733:        
1.267     brouard  8734: }
1.217     brouard  8735: 
1.269     brouard  8736: /* Variance of prevalence limit: varprlim */
                   8737:  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  8738:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8739:  
                   8740:    char fileresvpl[FILENAMELENGTH];  
                   8741:    FILE *ficresvpl;
                   8742:    double **oldm, **savm;
                   8743:    double **varpl; /* Variances of prevalence limits by age */   
                   8744:    int i1, k, nres, j ;
                   8745:    
                   8746:     strcpy(fileresvpl,"VPL_");
                   8747:     strcat(fileresvpl,fileresu);
                   8748:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8749:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8750:       exit(0);
                   8751:     }
1.288     brouard  8752:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8753:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8754:     
                   8755:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8756:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8757:     
                   8758:     i1=pow(2,cptcoveff);
                   8759:     if (cptcovn < 1){i1=1;}
                   8760: 
                   8761:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8762:     for(k=1; k<=i1;k++){
                   8763:       if(i1 != 1 && TKresult[nres]!= k)
                   8764:        continue;
                   8765:       fprintf(ficresvpl,"\n#****** ");
                   8766:       printf("\n#****** ");
                   8767:       fprintf(ficlog,"\n#****** ");
                   8768:       for(j=1;j<=cptcoveff;j++) {
                   8769:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8770:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8771:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8772:       }
                   8773:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8774:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8775:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8776:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8777:       }        
                   8778:       fprintf(ficresvpl,"******\n");
                   8779:       printf("******\n");
                   8780:       fprintf(ficlog,"******\n");
                   8781:       
                   8782:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8783:       oldm=oldms;savm=savms;
                   8784:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8785:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8786:       /*}*/
                   8787:     }
                   8788:     
                   8789:     fclose(ficresvpl);
1.288     brouard  8790:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8791:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8792: 
                   8793:  }
                   8794: /* Variance of back prevalence: varbprlim */
                   8795:  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){
                   8796:       /*------- Variance of back (stable) prevalence------*/
                   8797: 
                   8798:    char fileresvbl[FILENAMELENGTH];  
                   8799:    FILE  *ficresvbl;
                   8800: 
                   8801:    double **oldm, **savm;
                   8802:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8803:    int i1, k, nres, j ;
                   8804: 
                   8805:    strcpy(fileresvbl,"VBL_");
                   8806:    strcat(fileresvbl,fileresu);
                   8807:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8808:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8809:      exit(0);
                   8810:    }
                   8811:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8812:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8813:    
                   8814:    
                   8815:    i1=pow(2,cptcoveff);
                   8816:    if (cptcovn < 1){i1=1;}
                   8817:    
                   8818:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8819:      for(k=1; k<=i1;k++){
                   8820:        if(i1 != 1 && TKresult[nres]!= k)
                   8821:         continue;
                   8822:        fprintf(ficresvbl,"\n#****** ");
                   8823:        printf("\n#****** ");
                   8824:        fprintf(ficlog,"\n#****** ");
                   8825:        for(j=1;j<=cptcoveff;j++) {
                   8826:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8827:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8828:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8829:        }
                   8830:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8831:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8832:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8833:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8834:        }
                   8835:        fprintf(ficresvbl,"******\n");
                   8836:        printf("******\n");
                   8837:        fprintf(ficlog,"******\n");
                   8838:        
                   8839:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8840:        oldm=oldms;savm=savms;
                   8841:        
                   8842:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8843:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8844:        /*}*/
                   8845:      }
                   8846:    
                   8847:    fclose(ficresvbl);
                   8848:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8849:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8850: 
                   8851:  } /* End of varbprlim */
                   8852: 
1.126     brouard  8853: /************** Forecasting *****not tested NB*************/
1.227     brouard  8854: /* 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  8855:   
1.227     brouard  8856: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8857: /*   int *popage; */
                   8858: /*   double calagedatem, agelim, kk1, kk2; */
                   8859: /*   double *popeffectif,*popcount; */
                   8860: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8861: /*   /\* double ***mobaverage; *\/ */
                   8862: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8863: 
1.227     brouard  8864: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8865: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8866: /*   agelim=AGESUP; */
                   8867: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8868:   
1.227     brouard  8869: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8870:   
                   8871:   
1.227     brouard  8872: /*   strcpy(filerespop,"POP_");  */
                   8873: /*   strcat(filerespop,fileresu); */
                   8874: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8875: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8876: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8877: /*   } */
                   8878: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8879: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8880: 
1.227     brouard  8881: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8882: 
1.227     brouard  8883: /*   /\* if (mobilav!=0) { *\/ */
                   8884: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8885: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8886: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8887: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8888: /*   /\*   } *\/ */
                   8889: /*   /\* } *\/ */
1.126     brouard  8890: 
1.227     brouard  8891: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8892: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8893:   
1.227     brouard  8894: /*   agelim=AGESUP; */
1.126     brouard  8895:   
1.227     brouard  8896: /*   hstepm=1; */
                   8897: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8898:        
1.227     brouard  8899: /*   if (popforecast==1) { */
                   8900: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8901: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8902: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8903: /*     }  */
                   8904: /*     popage=ivector(0,AGESUP); */
                   8905: /*     popeffectif=vector(0,AGESUP); */
                   8906: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8907:     
1.227     brouard  8908: /*     i=1;    */
                   8909: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8910:     
1.227     brouard  8911: /*     imx=i; */
                   8912: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8913: /*   } */
1.218     brouard  8914:   
1.227     brouard  8915: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8916: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8917: /*       k=k+1; */
                   8918: /*       fprintf(ficrespop,"\n#******"); */
                   8919: /*       for(j=1;j<=cptcoveff;j++) { */
                   8920: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8921: /*       } */
                   8922: /*       fprintf(ficrespop,"******\n"); */
                   8923: /*       fprintf(ficrespop,"# Age"); */
                   8924: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8925: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8926:       
1.227     brouard  8927: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8928: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8929:        
1.227     brouard  8930: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8931: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8932: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8933:          
1.227     brouard  8934: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8935: /*       oldm=oldms;savm=savms; */
                   8936: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8937:          
1.227     brouard  8938: /*       for (h=0; h<=nhstepm; h++){ */
                   8939: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8940: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8941: /*         }  */
                   8942: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8943: /*           kk1=0.;kk2=0; */
                   8944: /*           for(i=1; i<=nlstate;i++) {               */
                   8945: /*             if (mobilav==1)  */
                   8946: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8947: /*             else { */
                   8948: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8949: /*             } */
                   8950: /*           } */
                   8951: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8952: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8953: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8954: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8955: /*           } */
                   8956: /*         } */
                   8957: /*         for(i=1; i<=nlstate;i++){ */
                   8958: /*           kk1=0.; */
                   8959: /*           for(j=1; j<=nlstate;j++){ */
                   8960: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8961: /*           } */
                   8962: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8963: /*         } */
1.218     brouard  8964:            
1.227     brouard  8965: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8966: /*           for(j=1; j<=nlstate;j++)  */
                   8967: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8968: /*       } */
                   8969: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8970: /*     } */
                   8971: /*       } */
1.218     brouard  8972:       
1.227     brouard  8973: /*       /\******\/ */
1.218     brouard  8974:       
1.227     brouard  8975: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8976: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8977: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8978: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8979: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8980:          
1.227     brouard  8981: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8982: /*       oldm=oldms;savm=savms; */
                   8983: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8984: /*       for (h=0; h<=nhstepm; h++){ */
                   8985: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8986: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8987: /*         }  */
                   8988: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8989: /*           kk1=0.;kk2=0; */
                   8990: /*           for(i=1; i<=nlstate;i++) {               */
                   8991: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8992: /*           } */
                   8993: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8994: /*         } */
                   8995: /*       } */
                   8996: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8997: /*     } */
                   8998: /*       } */
                   8999: /*     }  */
                   9000: /*   } */
1.218     brouard  9001:   
1.227     brouard  9002: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9003:   
1.227     brouard  9004: /*   if (popforecast==1) { */
                   9005: /*     free_ivector(popage,0,AGESUP); */
                   9006: /*     free_vector(popeffectif,0,AGESUP); */
                   9007: /*     free_vector(popcount,0,AGESUP); */
                   9008: /*   } */
                   9009: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9010: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9011: /*   fclose(ficrespop); */
                   9012: /* } /\* End of popforecast *\/ */
1.218     brouard  9013:  
1.126     brouard  9014: int fileappend(FILE *fichier, char *optionfich)
                   9015: {
                   9016:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9017:     printf("Problem with file: %s\n", optionfich);
                   9018:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9019:     return (0);
                   9020:   }
                   9021:   fflush(fichier);
                   9022:   return (1);
                   9023: }
                   9024: 
                   9025: 
                   9026: /**************** function prwizard **********************/
                   9027: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9028: {
                   9029: 
                   9030:   /* Wizard to print covariance matrix template */
                   9031: 
1.164     brouard  9032:   char ca[32], cb[32];
                   9033:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9034:   int numlinepar;
                   9035: 
                   9036:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9037:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9038:   for(i=1; i <=nlstate; i++){
                   9039:     jj=0;
                   9040:     for(j=1; j <=nlstate+ndeath; j++){
                   9041:       if(j==i) continue;
                   9042:       jj++;
                   9043:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9044:       printf("%1d%1d",i,j);
                   9045:       fprintf(ficparo,"%1d%1d",i,j);
                   9046:       for(k=1; k<=ncovmodel;k++){
                   9047:        /*        printf(" %lf",param[i][j][k]); */
                   9048:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9049:        printf(" 0.");
                   9050:        fprintf(ficparo," 0.");
                   9051:       }
                   9052:       printf("\n");
                   9053:       fprintf(ficparo,"\n");
                   9054:     }
                   9055:   }
                   9056:   printf("# Scales (for hessian or gradient estimation)\n");
                   9057:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9058:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9059:   for(i=1; i <=nlstate; i++){
                   9060:     jj=0;
                   9061:     for(j=1; j <=nlstate+ndeath; j++){
                   9062:       if(j==i) continue;
                   9063:       jj++;
                   9064:       fprintf(ficparo,"%1d%1d",i,j);
                   9065:       printf("%1d%1d",i,j);
                   9066:       fflush(stdout);
                   9067:       for(k=1; k<=ncovmodel;k++){
                   9068:        /*      printf(" %le",delti3[i][j][k]); */
                   9069:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9070:        printf(" 0.");
                   9071:        fprintf(ficparo," 0.");
                   9072:       }
                   9073:       numlinepar++;
                   9074:       printf("\n");
                   9075:       fprintf(ficparo,"\n");
                   9076:     }
                   9077:   }
                   9078:   printf("# Covariance matrix\n");
                   9079: /* # 121 Var(a12)\n\ */
                   9080: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9081: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9082: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9083: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9084: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9085: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9086: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9087:   fflush(stdout);
                   9088:   fprintf(ficparo,"# Covariance matrix\n");
                   9089:   /* # 121 Var(a12)\n\ */
                   9090:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9091:   /* #   ...\n\ */
                   9092:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9093:   
                   9094:   for(itimes=1;itimes<=2;itimes++){
                   9095:     jj=0;
                   9096:     for(i=1; i <=nlstate; i++){
                   9097:       for(j=1; j <=nlstate+ndeath; j++){
                   9098:        if(j==i) continue;
                   9099:        for(k=1; k<=ncovmodel;k++){
                   9100:          jj++;
                   9101:          ca[0]= k+'a'-1;ca[1]='\0';
                   9102:          if(itimes==1){
                   9103:            printf("#%1d%1d%d",i,j,k);
                   9104:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9105:          }else{
                   9106:            printf("%1d%1d%d",i,j,k);
                   9107:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9108:            /*  printf(" %.5le",matcov[i][j]); */
                   9109:          }
                   9110:          ll=0;
                   9111:          for(li=1;li <=nlstate; li++){
                   9112:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9113:              if(lj==li) continue;
                   9114:              for(lk=1;lk<=ncovmodel;lk++){
                   9115:                ll++;
                   9116:                if(ll<=jj){
                   9117:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9118:                  if(ll<jj){
                   9119:                    if(itimes==1){
                   9120:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9121:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9122:                    }else{
                   9123:                      printf(" 0.");
                   9124:                      fprintf(ficparo," 0.");
                   9125:                    }
                   9126:                  }else{
                   9127:                    if(itimes==1){
                   9128:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9129:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9130:                    }else{
                   9131:                      printf(" 0.");
                   9132:                      fprintf(ficparo," 0.");
                   9133:                    }
                   9134:                  }
                   9135:                }
                   9136:              } /* end lk */
                   9137:            } /* end lj */
                   9138:          } /* end li */
                   9139:          printf("\n");
                   9140:          fprintf(ficparo,"\n");
                   9141:          numlinepar++;
                   9142:        } /* end k*/
                   9143:       } /*end j */
                   9144:     } /* end i */
                   9145:   } /* end itimes */
                   9146: 
                   9147: } /* end of prwizard */
                   9148: /******************* Gompertz Likelihood ******************************/
                   9149: double gompertz(double x[])
                   9150: { 
1.302     brouard  9151:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9152:   int i,n=0; /* n is the size of the sample */
                   9153: 
1.220     brouard  9154:   for (i=1;i<=imx ; i++) {
1.126     brouard  9155:     sump=sump+weight[i];
                   9156:     /*    sump=sump+1;*/
                   9157:     num=num+1;
                   9158:   }
1.302     brouard  9159:   L=0.0;
                   9160:   /* agegomp=AGEGOMP; */
1.126     brouard  9161:   /* for (i=0; i<=imx; i++) 
                   9162:      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]);*/
                   9163: 
1.302     brouard  9164:   for (i=1;i<=imx ; i++) {
                   9165:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9166:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9167:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9168:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9169:      * +
                   9170:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9171:      */
                   9172:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9173:        if (cens[i] == 1){
                   9174:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9175:        } else if (cens[i] == 0){
1.126     brouard  9176:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9177:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9178:       } else
                   9179:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9180:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9181:        L=L+A*weight[i];
1.126     brouard  9182:        /*      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  9183:      }
                   9184:   }
1.126     brouard  9185: 
1.302     brouard  9186:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9187:  
                   9188:   return -2*L*num/sump;
                   9189: }
                   9190: 
1.136     brouard  9191: #ifdef GSL
                   9192: /******************* Gompertz_f Likelihood ******************************/
                   9193: double gompertz_f(const gsl_vector *v, void *params)
                   9194: { 
1.302     brouard  9195:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9196:   double *x= (double *) v->data;
                   9197:   int i,n=0; /* n is the size of the sample */
                   9198: 
                   9199:   for (i=0;i<=imx-1 ; i++) {
                   9200:     sump=sump+weight[i];
                   9201:     /*    sump=sump+1;*/
                   9202:     num=num+1;
                   9203:   }
                   9204:  
                   9205:  
                   9206:   /* for (i=0; i<=imx; i++) 
                   9207:      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]);*/
                   9208:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9209:   for (i=1;i<=imx ; i++)
                   9210:     {
                   9211:       if (cens[i] == 1 && wav[i]>1)
                   9212:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9213:       
                   9214:       if (cens[i] == 0 && wav[i]>1)
                   9215:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9216:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9217:       
                   9218:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9219:       if (wav[i] > 1 ) { /* ??? */
                   9220:        LL=LL+A*weight[i];
                   9221:        /*      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]);*/
                   9222:       }
                   9223:     }
                   9224: 
                   9225:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9226:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9227:  
                   9228:   return -2*LL*num/sump;
                   9229: }
                   9230: #endif
                   9231: 
1.126     brouard  9232: /******************* Printing html file ***********/
1.201     brouard  9233: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9234:                  int lastpass, int stepm, int weightopt, char model[],\
                   9235:                  int imx,  double p[],double **matcov,double agemortsup){
                   9236:   int i,k;
                   9237: 
                   9238:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9239:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9240:   for (i=1;i<=2;i++) 
                   9241:     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  9242:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9243:   fprintf(fichtm,"</ul>");
                   9244: 
                   9245: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9246: 
                   9247:  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>");
                   9248: 
                   9249:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9250:    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]);
                   9251: 
                   9252:  
                   9253:   fflush(fichtm);
                   9254: }
                   9255: 
                   9256: /******************* Gnuplot file **************/
1.201     brouard  9257: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9258: 
                   9259:   char dirfileres[132],optfileres[132];
1.164     brouard  9260: 
1.126     brouard  9261:   int ng;
                   9262: 
                   9263: 
                   9264:   /*#ifdef windows */
                   9265:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9266:     /*#endif */
                   9267: 
                   9268: 
                   9269:   strcpy(dirfileres,optionfilefiname);
                   9270:   strcpy(optfileres,"vpl");
1.199     brouard  9271:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9272:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9273:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9274:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9275:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9276: 
                   9277: } 
                   9278: 
1.136     brouard  9279: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9280: {
1.126     brouard  9281: 
1.136     brouard  9282:   /*-------- data file ----------*/
                   9283:   FILE *fic;
                   9284:   char dummy[]="                         ";
1.240     brouard  9285:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9286:   int lstra;
1.136     brouard  9287:   int linei, month, year,iout;
1.302     brouard  9288:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9289:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9290:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9291:   char *stratrunc;
1.223     brouard  9292: 
1.240     brouard  9293:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9294:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9295: 
1.240     brouard  9296:   for(v=1; v <=ncovcol;v++){
                   9297:     DummyV[v]=0;
                   9298:     FixedV[v]=0;
                   9299:   }
                   9300:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9301:     DummyV[v]=1;
                   9302:     FixedV[v]=0;
                   9303:   }
                   9304:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9305:     DummyV[v]=0;
                   9306:     FixedV[v]=1;
                   9307:   }
                   9308:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9309:     DummyV[v]=1;
                   9310:     FixedV[v]=1;
                   9311:   }
                   9312:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9313:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9314:     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]);
                   9315:   }
1.126     brouard  9316: 
1.136     brouard  9317:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9318:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9319:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9320:   }
1.126     brouard  9321: 
1.302     brouard  9322:     /* Is it a BOM UTF-8 Windows file? */
                   9323:   /* First data line */
                   9324:   linei=0;
                   9325:   while(fgets(line, MAXLINE, fic)) {
                   9326:     noffset=0;
                   9327:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9328:     {
                   9329:       noffset=noffset+3;
                   9330:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9331:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9332:       fflush(ficlog); return 1;
                   9333:     }
                   9334:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9335:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9336:     {
                   9337:       noffset=noffset+2;
1.304     brouard  9338:       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);
                   9339:       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  9340:       fflush(ficlog); return 1;
                   9341:     }
                   9342:     else if( line[0] == 0 && line[1] == 0)
                   9343:     {
                   9344:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9345:        noffset=noffset+4;
1.304     brouard  9346:        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);
                   9347:        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  9348:        fflush(ficlog); return 1;
                   9349:       }
                   9350:     } else{
                   9351:       ;/*printf(" Not a BOM file\n");*/
                   9352:     }
                   9353:         /* If line starts with a # it is a comment */
                   9354:     if (line[noffset] == '#') {
                   9355:       linei=linei+1;
                   9356:       break;
                   9357:     }else{
                   9358:       break;
                   9359:     }
                   9360:   }
                   9361:   fclose(fic);
                   9362:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9363:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9364:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9365:   }
                   9366:   /* Not a Bom file */
                   9367:   
1.136     brouard  9368:   i=1;
                   9369:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9370:     linei=linei+1;
                   9371:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9372:       if(line[j] == '\t')
                   9373:        line[j] = ' ';
                   9374:     }
                   9375:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9376:       ;
                   9377:     };
                   9378:     line[j+1]=0;  /* Trims blanks at end of line */
                   9379:     if(line[0]=='#'){
                   9380:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9381:       printf("Comment line\n%s\n",line);
                   9382:       continue;
                   9383:     }
                   9384:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9385:     strcpy(line, linetmp);
1.223     brouard  9386:     
                   9387:     /* Loops on waves */
                   9388:     for (j=maxwav;j>=1;j--){
                   9389:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9390:        cutv(stra, strb, line, ' '); 
                   9391:        if(strb[0]=='.') { /* Missing value */
                   9392:          lval=-1;
                   9393:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9394:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9395:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9396:            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);
                   9397:            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);
                   9398:            return 1;
                   9399:          }
                   9400:        }else{
                   9401:          errno=0;
                   9402:          /* what_kind_of_number(strb); */
                   9403:          dval=strtod(strb,&endptr); 
                   9404:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9405:          /* if(strb != endptr && *endptr == '\0') */
                   9406:          /*    dval=dlval; */
                   9407:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9408:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9409:            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);
                   9410:            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);
                   9411:            return 1;
                   9412:          }
                   9413:          cotqvar[j][iv][i]=dval; 
                   9414:          cotvar[j][ntv+iv][i]=dval; 
                   9415:        }
                   9416:        strcpy(line,stra);
1.223     brouard  9417:       }/* end loop ntqv */
1.225     brouard  9418:       
1.223     brouard  9419:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9420:        cutv(stra, strb, line, ' '); 
                   9421:        if(strb[0]=='.') { /* Missing value */
                   9422:          lval=-1;
                   9423:        }else{
                   9424:          errno=0;
                   9425:          lval=strtol(strb,&endptr,10); 
                   9426:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9427:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9428:            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);
                   9429:            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);
                   9430:            return 1;
                   9431:          }
                   9432:        }
                   9433:        if(lval <-1 || lval >1){
                   9434:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9435:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9436:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9437:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9438:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9439:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9440:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9441:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9442:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9443:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9444:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9445:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9446:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9447:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9448:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9449:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9450:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9451:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9452:          return 1;
                   9453:        }
                   9454:        cotvar[j][iv][i]=(double)(lval);
                   9455:        strcpy(line,stra);
1.223     brouard  9456:       }/* end loop ntv */
1.225     brouard  9457:       
1.223     brouard  9458:       /* Statuses  at wave */
1.137     brouard  9459:       cutv(stra, strb, line, ' '); 
1.223     brouard  9460:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9461:        lval=-1;
1.136     brouard  9462:       }else{
1.238     brouard  9463:        errno=0;
                   9464:        lval=strtol(strb,&endptr,10); 
                   9465:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9466:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9467:          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);
                   9468:          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);
                   9469:          return 1;
                   9470:        }
1.136     brouard  9471:       }
1.225     brouard  9472:       
1.136     brouard  9473:       s[j][i]=lval;
1.225     brouard  9474:       
1.223     brouard  9475:       /* Date of Interview */
1.136     brouard  9476:       strcpy(line,stra);
                   9477:       cutv(stra, strb,line,' ');
1.169     brouard  9478:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9479:       }
1.169     brouard  9480:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9481:        month=99;
                   9482:        year=9999;
1.136     brouard  9483:       }else{
1.225     brouard  9484:        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);
                   9485:        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);
                   9486:        return 1;
1.136     brouard  9487:       }
                   9488:       anint[j][i]= (double) year; 
1.302     brouard  9489:       mint[j][i]= (double)month;
                   9490:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9491:       /*       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]); */
                   9492:       /*       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]); */
                   9493:       /* } */
1.136     brouard  9494:       strcpy(line,stra);
1.223     brouard  9495:     } /* End loop on waves */
1.225     brouard  9496:     
1.223     brouard  9497:     /* Date of death */
1.136     brouard  9498:     cutv(stra, strb,line,' '); 
1.169     brouard  9499:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9500:     }
1.169     brouard  9501:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9502:       month=99;
                   9503:       year=9999;
                   9504:     }else{
1.141     brouard  9505:       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  9506:       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);
                   9507:       return 1;
1.136     brouard  9508:     }
                   9509:     andc[i]=(double) year; 
                   9510:     moisdc[i]=(double) month; 
                   9511:     strcpy(line,stra);
                   9512:     
1.223     brouard  9513:     /* Date of birth */
1.136     brouard  9514:     cutv(stra, strb,line,' '); 
1.169     brouard  9515:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9516:     }
1.169     brouard  9517:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9518:       month=99;
                   9519:       year=9999;
                   9520:     }else{
1.141     brouard  9521:       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);
                   9522:       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  9523:       return 1;
1.136     brouard  9524:     }
                   9525:     if (year==9999) {
1.141     brouard  9526:       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);
                   9527:       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  9528:       return 1;
                   9529:       
1.136     brouard  9530:     }
                   9531:     annais[i]=(double)(year);
1.302     brouard  9532:     moisnais[i]=(double)(month);
                   9533:     for (j=1;j<=maxwav;j++){
                   9534:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9535:        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]);
                   9536:        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]);
                   9537:       }
                   9538:     }
                   9539: 
1.136     brouard  9540:     strcpy(line,stra);
1.225     brouard  9541:     
1.223     brouard  9542:     /* Sample weight */
1.136     brouard  9543:     cutv(stra, strb,line,' '); 
                   9544:     errno=0;
                   9545:     dval=strtod(strb,&endptr); 
                   9546:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9547:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9548:       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  9549:       fflush(ficlog);
                   9550:       return 1;
                   9551:     }
                   9552:     weight[i]=dval; 
                   9553:     strcpy(line,stra);
1.225     brouard  9554:     
1.223     brouard  9555:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9556:       cutv(stra, strb, line, ' '); 
                   9557:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9558:        lval=-1;
1.311     brouard  9559:        coqvar[iv][i]=NAN; 
                   9560:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9561:       }else{
1.225     brouard  9562:        errno=0;
                   9563:        /* what_kind_of_number(strb); */
                   9564:        dval=strtod(strb,&endptr);
                   9565:        /* if(strb != endptr && *endptr == '\0') */
                   9566:        /*   dval=dlval; */
                   9567:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9568:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9569:          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);
                   9570:          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);
                   9571:          return 1;
                   9572:        }
                   9573:        coqvar[iv][i]=dval; 
1.226     brouard  9574:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9575:       }
                   9576:       strcpy(line,stra);
                   9577:     }/* end loop nqv */
1.136     brouard  9578:     
1.223     brouard  9579:     /* Covariate values */
1.136     brouard  9580:     for (j=ncovcol;j>=1;j--){
                   9581:       cutv(stra, strb,line,' '); 
1.223     brouard  9582:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9583:        lval=-1;
1.136     brouard  9584:       }else{
1.225     brouard  9585:        errno=0;
                   9586:        lval=strtol(strb,&endptr,10); 
                   9587:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9588:          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);
                   9589:          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);
                   9590:          return 1;
                   9591:        }
1.136     brouard  9592:       }
                   9593:       if(lval <-1 || lval >1){
1.225     brouard  9594:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9595:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9596:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9597:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9598:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9599:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9600:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9601:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9602:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9603:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9604:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9605:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9606:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9607:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9608:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9609:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9610:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9611:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9612:        return 1;
1.136     brouard  9613:       }
                   9614:       covar[j][i]=(double)(lval);
                   9615:       strcpy(line,stra);
                   9616:     }  
                   9617:     lstra=strlen(stra);
1.225     brouard  9618:     
1.136     brouard  9619:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9620:       stratrunc = &(stra[lstra-9]);
                   9621:       num[i]=atol(stratrunc);
                   9622:     }
                   9623:     else
                   9624:       num[i]=atol(stra);
                   9625:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9626:       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;}*/
                   9627:     
                   9628:     i=i+1;
                   9629:   } /* End loop reading  data */
1.225     brouard  9630:   
1.136     brouard  9631:   *imax=i-1; /* Number of individuals */
                   9632:   fclose(fic);
1.225     brouard  9633:   
1.136     brouard  9634:   return (0);
1.164     brouard  9635:   /* endread: */
1.225     brouard  9636:   printf("Exiting readdata: ");
                   9637:   fclose(fic);
                   9638:   return (1);
1.223     brouard  9639: }
1.126     brouard  9640: 
1.234     brouard  9641: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9642:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9643:   while (*p2 == ' ')
1.234     brouard  9644:     p2++; 
                   9645:   /* while ((*p1++ = *p2++) !=0) */
                   9646:   /*   ; */
                   9647:   /* do */
                   9648:   /*   while (*p2 == ' ') */
                   9649:   /*     p2++; */
                   9650:   /* while (*p1++ == *p2++); */
                   9651:   *stri=p2; 
1.145     brouard  9652: }
                   9653: 
1.235     brouard  9654: int decoderesult ( char resultline[], int nres)
1.230     brouard  9655: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9656: {
1.235     brouard  9657:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9658:   char resultsav[MAXLINE];
1.234     brouard  9659:   int resultmodel[MAXLINE];
                   9660:   int modelresult[MAXLINE];
1.230     brouard  9661:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9662: 
1.234     brouard  9663:   removefirstspace(&resultline);
1.230     brouard  9664: 
                   9665:   if (strstr(resultline,"v") !=0){
                   9666:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9667:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9668:     return 1;
                   9669:   }
                   9670:   trimbb(resultsav, resultline);
                   9671:   if (strlen(resultsav) >1){
                   9672:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9673:   }
1.253     brouard  9674:   if(j == 0){ /* Resultline but no = */
                   9675:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9676:     return (0);
                   9677:   }
1.234     brouard  9678:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.310     brouard  9679:     printf("ERROR: the number of variables in the resultline, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
                   9680:     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  9681:   }
                   9682:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9683:     if(nbocc(resultsav,'=') >1){
                   9684:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
1.310     brouard  9685:                                      resultsav= V4=1 V5=25.1 V3=0 stra= V5=25.1 V3=0 strb= V4=1 */
1.234     brouard  9686:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9687:     }else
                   9688:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9689:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9690:     
1.230     brouard  9691:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9692:     Tvarsel[k]=atoi(strc);
                   9693:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9694:     /* cptcovsel++;     */
                   9695:     if (nbocc(stra,'=') >0)
                   9696:       strcpy(resultsav,stra); /* and analyzes it */
                   9697:   }
1.235     brouard  9698:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9699:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9700:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9701:       match=0;
1.236     brouard  9702:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9703:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9704:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9705:          match=1;
                   9706:          break;
                   9707:        }
                   9708:       }
                   9709:       if(match == 0){
1.310     brouard  9710:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9711:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9712:        return 1;
1.234     brouard  9713:       }
                   9714:     }
                   9715:   }
1.235     brouard  9716:   /* Checking for missing or useless values in comparison of current model needs */
                   9717:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9718:     match=0;
1.235     brouard  9719:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9720:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9721:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9722:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9723:          ++match;
                   9724:        }
                   9725:       }
                   9726:     }
                   9727:     if(match == 0){
                   9728:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310     brouard  9729:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9730:       return 1;
1.234     brouard  9731:     }else if(match > 1){
                   9732:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  9733:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9734:       return 1;
1.234     brouard  9735:     }
                   9736:   }
1.235     brouard  9737:       
1.234     brouard  9738:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9739:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9740:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9741:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9742:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9743:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9744:   /*    1 0 0 0 */
                   9745:   /*    2 1 0 0 */
                   9746:   /*    3 0 1 0 */ 
                   9747:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9748:   /*    5 0 0 1 */
                   9749:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9750:   /*    7 0 1 1 */
                   9751:   /*    8 1 1 1 */
1.237     brouard  9752:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9753:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9754:   /* V5*age V5 known which value for nres?  */
                   9755:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9756:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9757:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9758:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9759:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9760:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9761:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9762:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9763:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9764:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9765:       k4++;;
                   9766:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9767:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9768:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9769:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9770:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9771:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9772:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9773:       k4q++;;
                   9774:     }
                   9775:   }
1.234     brouard  9776:   
1.235     brouard  9777:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9778:   return (0);
                   9779: }
1.235     brouard  9780: 
1.230     brouard  9781: int decodemodel( char model[], int lastobs)
                   9782:  /**< This routine decodes the model and returns:
1.224     brouard  9783:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9784:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9785:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9786:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9787:        * - cptcovage number of covariates with age*products =2
                   9788:        * - cptcovs number of simple covariates
                   9789:        * - 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
                   9790:        *     which is a new column after the 9 (ncovcol) variables. 
                   9791:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9792:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9793:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9794:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9795:        */
1.136     brouard  9796: {
1.238     brouard  9797:   int i, j, k, ks, v;
1.227     brouard  9798:   int  j1, k1, k2, k3, k4;
1.136     brouard  9799:   char modelsav[80];
1.145     brouard  9800:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9801:   char *strpt;
1.136     brouard  9802: 
1.145     brouard  9803:   /*removespace(model);*/
1.136     brouard  9804:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9805:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9806:     if (strstr(model,"AGE") !=0){
1.192     brouard  9807:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9808:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9809:       return 1;
                   9810:     }
1.141     brouard  9811:     if (strstr(model,"v") !=0){
                   9812:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9813:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9814:       return 1;
                   9815:     }
1.187     brouard  9816:     strcpy(modelsav,model); 
                   9817:     if ((strpt=strstr(model,"age*age")) !=0){
                   9818:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9819:       if(strpt != model){
1.234     brouard  9820:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9821:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9822:  corresponding column of parameters.\n",model);
1.234     brouard  9823:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9824:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9825:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9826:        return 1;
1.225     brouard  9827:       }
1.187     brouard  9828:       nagesqr=1;
                   9829:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9830:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9831:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9832:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9833:       else 
1.234     brouard  9834:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9835:     }else
                   9836:       nagesqr=0;
                   9837:     if (strlen(modelsav) >1){
                   9838:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9839:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9840:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9841:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9842:                     * cst, age and age*age 
                   9843:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9844:       /* including age products which are counted in cptcovage.
                   9845:        * but the covariates which are products must be treated 
                   9846:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9847:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9848:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9849:       
                   9850:       
1.187     brouard  9851:       /*   Design
                   9852:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9853:        *  <          ncovcol=8                >
                   9854:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9855:        *   k=  1    2      3       4     5       6      7        8
                   9856:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9857:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9858:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9859:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9860:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9861:        *  Tage[++cptcovage]=k
                   9862:        *       if products, new covar are created after ncovcol with k1
                   9863:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9864:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9865:        *  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
                   9866:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9867:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9868:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9869:        *  <          ncovcol=8                >
                   9870:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9871:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9872:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9873:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9874:        * p Tprod[1]@2={                         6, 5}
                   9875:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9876:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9877:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9878:        *How to reorganize?
                   9879:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9880:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9881:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9882:        * Struct []
                   9883:        */
1.225     brouard  9884:       
1.187     brouard  9885:       /* This loop fills the array Tvar from the string 'model'.*/
                   9886:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9887:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9888:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9889:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9890:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9891:       /*       k=1 Tvar[1]=2 (from V2) */
                   9892:       /*       k=5 Tvar[5] */
                   9893:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9894:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9895:       /*       } */
1.198     brouard  9896:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9897:       /*
                   9898:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9899:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9900:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9901:       }
1.187     brouard  9902:       cptcovage=0;
                   9903:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9904:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9905:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9906:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9907:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9908:        /*scanf("%d",i);*/
                   9909:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9910:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9911:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9912:            /* covar is not filled and then is empty */
                   9913:            cptcovprod--;
                   9914:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9915:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9916:            Typevar[k]=1;  /* 1 for age product */
                   9917:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9918:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9919:            /*printf("stre=%s ", stre);*/
                   9920:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9921:            cptcovprod--;
                   9922:            cutl(stre,strb,strc,'V');
                   9923:            Tvar[k]=atoi(stre);
                   9924:            Typevar[k]=1;  /* 1 for age product */
                   9925:            cptcovage++;
                   9926:            Tage[cptcovage]=k;
                   9927:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9928:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9929:            cptcovn++;
                   9930:            cptcovprodnoage++;k1++;
                   9931:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9932:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9933:                                                because this model-covariate is a construction we invent a new column
                   9934:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9935:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9936:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9937:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9938:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9939:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9940:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9941:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9942:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9943:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9944:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9945:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9946:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9947:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9948:            for (i=1; i<=lastobs;i++){
                   9949:              /* Computes the new covariate which is a product of
                   9950:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9951:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9952:            }
                   9953:          } /* End age is not in the model */
                   9954:        } /* End if model includes a product */
                   9955:        else { /* no more sum */
                   9956:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9957:          /*  scanf("%d",i);*/
                   9958:          cutl(strd,strc,strb,'V');
                   9959:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9960:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9961:          Tvar[k]=atoi(strd);
                   9962:          Typevar[k]=0;  /* 0 for simple covariates */
                   9963:        }
                   9964:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9965:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9966:                                  scanf("%d",i);*/
1.187     brouard  9967:       } /* end of loop + on total covariates */
                   9968:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9969:   } /* end if strlen(model == 0) */
1.136     brouard  9970:   
                   9971:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9972:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9973:   
1.136     brouard  9974:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9975:      printf("cptcovprod=%d ", cptcovprod);
                   9976:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9977:      scanf("%d ",i);*/
                   9978: 
                   9979: 
1.230     brouard  9980: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9981:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9982: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9983:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9984:    k =           1    2   3     4       5       6      7      8        9
                   9985:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9986:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9987:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9988:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9989:          Tmodelind[combination of covar]=k;
1.225     brouard  9990: */  
                   9991: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9992:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9993:   /* 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  9994:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9995:   printf("Model=%s\n\
                   9996: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9997: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9998: 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);
                   9999:   fprintf(ficlog,"Model=%s\n\
                   10000: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10001: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10002: 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  10003:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10004:   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 */
                   10005:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10006:       Fixed[k]= 0;
                   10007:       Dummy[k]= 0;
1.225     brouard  10008:       ncoveff++;
1.232     brouard  10009:       ncovf++;
1.234     brouard  10010:       nsd++;
                   10011:       modell[k].maintype= FTYPE;
                   10012:       TvarsD[nsd]=Tvar[k];
                   10013:       TvarsDind[nsd]=k;
                   10014:       TvarF[ncovf]=Tvar[k];
                   10015:       TvarFind[ncovf]=k;
                   10016:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10017:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10018:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10019:       Fixed[k]= 0;
                   10020:       Dummy[k]= 0;
                   10021:       ncoveff++;
                   10022:       ncovf++;
                   10023:       modell[k].maintype= FTYPE;
                   10024:       TvarF[ncovf]=Tvar[k];
                   10025:       TvarFind[ncovf]=k;
1.230     brouard  10026:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10027:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10028:     }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  10029:       Fixed[k]= 0;
                   10030:       Dummy[k]= 1;
1.230     brouard  10031:       nqfveff++;
1.234     brouard  10032:       modell[k].maintype= FTYPE;
                   10033:       modell[k].subtype= FQ;
                   10034:       nsq++;
                   10035:       TvarsQ[nsq]=Tvar[k];
                   10036:       TvarsQind[nsq]=k;
1.232     brouard  10037:       ncovf++;
1.234     brouard  10038:       TvarF[ncovf]=Tvar[k];
                   10039:       TvarFind[ncovf]=k;
1.231     brouard  10040:       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  10041:       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  10042:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10043:       Fixed[k]= 1;
                   10044:       Dummy[k]= 0;
1.225     brouard  10045:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10046:       modell[k].maintype= VTYPE;
                   10047:       modell[k].subtype= VD;
                   10048:       nsd++;
                   10049:       TvarsD[nsd]=Tvar[k];
                   10050:       TvarsDind[nsd]=k;
                   10051:       ncovv++; /* Only simple time varying variables */
                   10052:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10053:       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  10054:       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 */
                   10055:       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  10056:       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);
                   10057:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10058:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10059:       Fixed[k]= 1;
                   10060:       Dummy[k]= 1;
                   10061:       nqtveff++;
                   10062:       modell[k].maintype= VTYPE;
                   10063:       modell[k].subtype= VQ;
                   10064:       ncovv++; /* Only simple time varying variables */
                   10065:       nsq++;
                   10066:       TvarsQ[nsq]=Tvar[k];
                   10067:       TvarsQind[nsq]=k;
                   10068:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10069:       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  10070:       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 */
                   10071:       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  10072:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10073:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10074:       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  10075:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10076:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10077:       ncova++;
                   10078:       TvarA[ncova]=Tvar[k];
                   10079:       TvarAind[ncova]=k;
1.231     brouard  10080:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10081:        Fixed[k]= 2;
                   10082:        Dummy[k]= 2;
                   10083:        modell[k].maintype= ATYPE;
                   10084:        modell[k].subtype= APFD;
                   10085:        /* ncoveff++; */
1.227     brouard  10086:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10087:        Fixed[k]= 2;
                   10088:        Dummy[k]= 3;
                   10089:        modell[k].maintype= ATYPE;
                   10090:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10091:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10092:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10093:        Fixed[k]= 3;
                   10094:        Dummy[k]= 2;
                   10095:        modell[k].maintype= ATYPE;
                   10096:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10097:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10098:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10099:        Fixed[k]= 3;
                   10100:        Dummy[k]= 3;
                   10101:        modell[k].maintype= ATYPE;
                   10102:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10103:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10104:       }
                   10105:     }else if (Typevar[k] == 2) {  /* product without age */
                   10106:       k1=Tposprod[k];
                   10107:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10108:        if(Tvard[k1][2] <=ncovcol){
                   10109:          Fixed[k]= 1;
                   10110:          Dummy[k]= 0;
                   10111:          modell[k].maintype= FTYPE;
                   10112:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10113:          ncovf++; /* Fixed variables without age */
                   10114:          TvarF[ncovf]=Tvar[k];
                   10115:          TvarFind[ncovf]=k;
                   10116:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10117:          Fixed[k]= 0;  /* or 2 ?*/
                   10118:          Dummy[k]= 1;
                   10119:          modell[k].maintype= FTYPE;
                   10120:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10121:          ncovf++; /* Varying variables without age */
                   10122:          TvarF[ncovf]=Tvar[k];
                   10123:          TvarFind[ncovf]=k;
                   10124:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10125:          Fixed[k]= 1;
                   10126:          Dummy[k]= 0;
                   10127:          modell[k].maintype= VTYPE;
                   10128:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10129:          ncovv++; /* Varying variables without age */
                   10130:          TvarV[ncovv]=Tvar[k];
                   10131:          TvarVind[ncovv]=k;
                   10132:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10133:          Fixed[k]= 1;
                   10134:          Dummy[k]= 1;
                   10135:          modell[k].maintype= VTYPE;
                   10136:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10137:          ncovv++; /* Varying variables without age */
                   10138:          TvarV[ncovv]=Tvar[k];
                   10139:          TvarVind[ncovv]=k;
                   10140:        }
1.227     brouard  10141:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10142:        if(Tvard[k1][2] <=ncovcol){
                   10143:          Fixed[k]= 0;  /* or 2 ?*/
                   10144:          Dummy[k]= 1;
                   10145:          modell[k].maintype= FTYPE;
                   10146:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10147:          ncovf++; /* Fixed variables without age */
                   10148:          TvarF[ncovf]=Tvar[k];
                   10149:          TvarFind[ncovf]=k;
                   10150:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10151:          Fixed[k]= 1;
                   10152:          Dummy[k]= 1;
                   10153:          modell[k].maintype= VTYPE;
                   10154:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10155:          ncovv++; /* Varying variables without age */
                   10156:          TvarV[ncovv]=Tvar[k];
                   10157:          TvarVind[ncovv]=k;
                   10158:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10159:          Fixed[k]= 1;
                   10160:          Dummy[k]= 1;
                   10161:          modell[k].maintype= VTYPE;
                   10162:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10163:          ncovv++; /* Varying variables without age */
                   10164:          TvarV[ncovv]=Tvar[k];
                   10165:          TvarVind[ncovv]=k;
                   10166:          ncovv++; /* Varying variables without age */
                   10167:          TvarV[ncovv]=Tvar[k];
                   10168:          TvarVind[ncovv]=k;
                   10169:        }
1.227     brouard  10170:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10171:        if(Tvard[k1][2] <=ncovcol){
                   10172:          Fixed[k]= 1;
                   10173:          Dummy[k]= 1;
                   10174:          modell[k].maintype= VTYPE;
                   10175:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10176:          ncovv++; /* Varying variables without age */
                   10177:          TvarV[ncovv]=Tvar[k];
                   10178:          TvarVind[ncovv]=k;
                   10179:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10180:          Fixed[k]= 1;
                   10181:          Dummy[k]= 1;
                   10182:          modell[k].maintype= VTYPE;
                   10183:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10184:          ncovv++; /* Varying variables without age */
                   10185:          TvarV[ncovv]=Tvar[k];
                   10186:          TvarVind[ncovv]=k;
                   10187:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10188:          Fixed[k]= 1;
                   10189:          Dummy[k]= 0;
                   10190:          modell[k].maintype= VTYPE;
                   10191:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10192:          ncovv++; /* Varying variables without age */
                   10193:          TvarV[ncovv]=Tvar[k];
                   10194:          TvarVind[ncovv]=k;
                   10195:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10196:          Fixed[k]= 1;
                   10197:          Dummy[k]= 1;
                   10198:          modell[k].maintype= VTYPE;
                   10199:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10200:          ncovv++; /* Varying variables without age */
                   10201:          TvarV[ncovv]=Tvar[k];
                   10202:          TvarVind[ncovv]=k;
                   10203:        }
1.227     brouard  10204:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10205:        if(Tvard[k1][2] <=ncovcol){
                   10206:          Fixed[k]= 1;
                   10207:          Dummy[k]= 1;
                   10208:          modell[k].maintype= VTYPE;
                   10209:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10210:          ncovv++; /* Varying variables without age */
                   10211:          TvarV[ncovv]=Tvar[k];
                   10212:          TvarVind[ncovv]=k;
                   10213:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10214:          Fixed[k]= 1;
                   10215:          Dummy[k]= 1;
                   10216:          modell[k].maintype= VTYPE;
                   10217:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10218:          ncovv++; /* Varying variables without age */
                   10219:          TvarV[ncovv]=Tvar[k];
                   10220:          TvarVind[ncovv]=k;
                   10221:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10222:          Fixed[k]= 1;
                   10223:          Dummy[k]= 1;
                   10224:          modell[k].maintype= VTYPE;
                   10225:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10226:          ncovv++; /* Varying variables without age */
                   10227:          TvarV[ncovv]=Tvar[k];
                   10228:          TvarVind[ncovv]=k;
                   10229:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10230:          Fixed[k]= 1;
                   10231:          Dummy[k]= 1;
                   10232:          modell[k].maintype= VTYPE;
                   10233:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10234:          ncovv++; /* Varying variables without age */
                   10235:          TvarV[ncovv]=Tvar[k];
                   10236:          TvarVind[ncovv]=k;
                   10237:        }
1.227     brouard  10238:       }else{
1.240     brouard  10239:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10240:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10241:       } /*end k1*/
1.225     brouard  10242:     }else{
1.226     brouard  10243:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10244:       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  10245:     }
1.227     brouard  10246:     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  10247:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10248:     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]);
                   10249:   }
                   10250:   /* Searching for doublons in the model */
                   10251:   for(k1=1; k1<= cptcovt;k1++){
                   10252:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10253:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10254:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10255:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10256:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10257:            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]);
                   10258:            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  10259:            return(1);
                   10260:          }
                   10261:        }else if (Typevar[k1] ==2){
                   10262:          k3=Tposprod[k1];
                   10263:          k4=Tposprod[k2];
                   10264:          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])) ){
                   10265:            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]]);
                   10266:            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);
                   10267:            return(1);
                   10268:          }
                   10269:        }
1.227     brouard  10270:       }
                   10271:     }
1.225     brouard  10272:   }
                   10273:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10274:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10275:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10276:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10277:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10278:   /*endread:*/
1.225     brouard  10279:   printf("Exiting decodemodel: ");
                   10280:   return (1);
1.136     brouard  10281: }
                   10282: 
1.169     brouard  10283: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10284: {/* Check ages at death */
1.136     brouard  10285:   int i, m;
1.218     brouard  10286:   int firstone=0;
                   10287:   
1.136     brouard  10288:   for (i=1; i<=imx; i++) {
                   10289:     for(m=2; (m<= maxwav); m++) {
                   10290:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10291:        anint[m][i]=9999;
1.216     brouard  10292:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10293:          s[m][i]=-1;
1.136     brouard  10294:       }
                   10295:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10296:        *nberr = *nberr + 1;
1.218     brouard  10297:        if(firstone == 0){
                   10298:          firstone=1;
1.260     brouard  10299:        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  10300:        }
1.262     brouard  10301:        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  10302:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10303:       }
                   10304:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10305:        (*nberr)++;
1.259     brouard  10306:        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  10307:        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  10308:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10309:       }
                   10310:     }
                   10311:   }
                   10312: 
                   10313:   for (i=1; i<=imx; i++)  {
                   10314:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10315:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10316:       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  10317:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10318:          if(agedc[i]>0){
                   10319:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10320:              agev[m][i]=agedc[i];
1.214     brouard  10321:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10322:            }else {
1.136     brouard  10323:              if ((int)andc[i]!=9999){
                   10324:                nbwarn++;
                   10325:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10326:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10327:                agev[m][i]=-1;
                   10328:              }
                   10329:            }
1.169     brouard  10330:          } /* agedc > 0 */
1.214     brouard  10331:        } /* end if */
1.136     brouard  10332:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10333:                                 years but with the precision of a month */
                   10334:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10335:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10336:            agev[m][i]=1;
                   10337:          else if(agev[m][i] < *agemin){ 
                   10338:            *agemin=agev[m][i];
                   10339:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10340:          }
                   10341:          else if(agev[m][i] >*agemax){
                   10342:            *agemax=agev[m][i];
1.156     brouard  10343:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10344:          }
                   10345:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10346:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10347:        } /* en if 9*/
1.136     brouard  10348:        else { /* =9 */
1.214     brouard  10349:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10350:          agev[m][i]=1;
                   10351:          s[m][i]=-1;
                   10352:        }
                   10353:       }
1.214     brouard  10354:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10355:        agev[m][i]=1;
1.214     brouard  10356:       else{
                   10357:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10358:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10359:        agev[m][i]=0;
                   10360:       }
                   10361:     } /* End for lastpass */
                   10362:   }
1.136     brouard  10363:     
                   10364:   for (i=1; i<=imx; i++)  {
                   10365:     for(m=firstpass; (m<=lastpass); m++){
                   10366:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10367:        (*nberr)++;
1.136     brouard  10368:        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);     
                   10369:        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);     
                   10370:        return 1;
                   10371:       }
                   10372:     }
                   10373:   }
                   10374: 
                   10375:   /*for (i=1; i<=imx; i++){
                   10376:   for (m=firstpass; (m<lastpass); m++){
                   10377:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10378: }
                   10379: 
                   10380: }*/
                   10381: 
                   10382: 
1.139     brouard  10383:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10384:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10385: 
                   10386:   return (0);
1.164     brouard  10387:  /* endread:*/
1.136     brouard  10388:     printf("Exiting calandcheckages: ");
                   10389:     return (1);
                   10390: }
                   10391: 
1.172     brouard  10392: #if defined(_MSC_VER)
                   10393: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10394: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10395: //#include "stdafx.h"
                   10396: //#include <stdio.h>
                   10397: //#include <tchar.h>
                   10398: //#include <windows.h>
                   10399: //#include <iostream>
                   10400: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10401: 
                   10402: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10403: 
                   10404: BOOL IsWow64()
                   10405: {
                   10406:        BOOL bIsWow64 = FALSE;
                   10407: 
                   10408:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10409:        //  (HANDLE, PBOOL);
                   10410: 
                   10411:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10412: 
                   10413:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10414:        const char funcName[] = "IsWow64Process";
                   10415:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10416:                GetProcAddress(module, funcName);
                   10417: 
                   10418:        if (NULL != fnIsWow64Process)
                   10419:        {
                   10420:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10421:                        &bIsWow64))
                   10422:                        //throw std::exception("Unknown error");
                   10423:                        printf("Unknown error\n");
                   10424:        }
                   10425:        return bIsWow64 != FALSE;
                   10426: }
                   10427: #endif
1.177     brouard  10428: 
1.191     brouard  10429: void syscompilerinfo(int logged)
1.292     brouard  10430: {
                   10431: #include <stdint.h>
                   10432: 
                   10433:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10434:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10435:    /* /GS /W3 /Gy
                   10436:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10437:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10438:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10439:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10440:    */ 
                   10441:    /* 64 bits */
1.185     brouard  10442:    /*
                   10443:      /GS /W3 /Gy
                   10444:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10445:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10446:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10447:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10448:    /* Optimization are useless and O3 is slower than O2 */
                   10449:    /*
                   10450:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10451:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10452:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10453:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10454:    */
1.186     brouard  10455:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10456:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10457:       /PDB:"visual studio
                   10458:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10459:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10460:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10461:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10462:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10463:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10464:       uiAccess='false'"
                   10465:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10466:       /NOLOGO /TLBID:1
                   10467:    */
1.292     brouard  10468: 
                   10469: 
1.177     brouard  10470: #if defined __INTEL_COMPILER
1.178     brouard  10471: #if defined(__GNUC__)
                   10472:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10473: #endif
1.177     brouard  10474: #elif defined(__GNUC__) 
1.179     brouard  10475: #ifndef  __APPLE__
1.174     brouard  10476: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10477: #endif
1.177     brouard  10478:    struct utsname sysInfo;
1.178     brouard  10479:    int cross = CROSS;
                   10480:    if (cross){
                   10481:           printf("Cross-");
1.191     brouard  10482:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10483:    }
1.174     brouard  10484: #endif
                   10485: 
1.191     brouard  10486:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10487: #if defined(__clang__)
1.191     brouard  10488:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10489: #endif
                   10490: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10491:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10492: #endif
                   10493: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10494:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10495: #endif
                   10496: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10497:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10498: #endif
                   10499: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10500:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10501: #endif
                   10502: #if defined(_MSC_VER)
1.191     brouard  10503:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10504: #endif
                   10505: #if defined(__PGI)
1.191     brouard  10506:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10507: #endif
                   10508: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10509:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10510: #endif
1.191     brouard  10511:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10512:    
1.167     brouard  10513: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10514: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10515:     // Windows (x64 and x86)
1.191     brouard  10516:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10517: #elif __unix__ // all unices, not all compilers
                   10518:     // Unix
1.191     brouard  10519:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10520: #elif __linux__
                   10521:     // linux
1.191     brouard  10522:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10523: #elif __APPLE__
1.174     brouard  10524:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10525:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10526: #endif
                   10527: 
                   10528: /*  __MINGW32__          */
                   10529: /*  __CYGWIN__  */
                   10530: /* __MINGW64__  */
                   10531: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10532: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10533: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10534: /* _WIN64  // Defined for applications for Win64. */
                   10535: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10536: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10537: 
1.167     brouard  10538: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10539:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10540: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10541:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10542: #else
1.191     brouard  10543:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10544: #endif
                   10545: 
1.169     brouard  10546: #if defined(__GNUC__)
                   10547: # if defined(__GNUC_PATCHLEVEL__)
                   10548: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10549:                             + __GNUC_MINOR__ * 100 \
                   10550:                             + __GNUC_PATCHLEVEL__)
                   10551: # else
                   10552: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10553:                             + __GNUC_MINOR__ * 100)
                   10554: # endif
1.174     brouard  10555:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10556:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10557: 
                   10558:    if (uname(&sysInfo) != -1) {
                   10559:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10560:         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  10561:    }
                   10562:    else
                   10563:       perror("uname() error");
1.179     brouard  10564:    //#ifndef __INTEL_COMPILER 
                   10565: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10566:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10567:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10568: #endif
1.169     brouard  10569: #endif
1.172     brouard  10570: 
1.286     brouard  10571:    //   void main ()
1.172     brouard  10572:    //   {
1.169     brouard  10573: #if defined(_MSC_VER)
1.174     brouard  10574:    if (IsWow64()){
1.191     brouard  10575:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10576:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10577:    }
                   10578:    else{
1.191     brouard  10579:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10580:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10581:    }
1.172     brouard  10582:    //     printf("\nPress Enter to continue...");
                   10583:    //     getchar();
                   10584:    //   }
                   10585: 
1.169     brouard  10586: #endif
                   10587:    
1.167     brouard  10588: 
1.219     brouard  10589: }
1.136     brouard  10590: 
1.219     brouard  10591: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10592:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10593:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10594:   /* double ftolpl = 1.e-10; */
1.180     brouard  10595:   double age, agebase, agelim;
1.203     brouard  10596:   double tot;
1.180     brouard  10597: 
1.202     brouard  10598:   strcpy(filerespl,"PL_");
                   10599:   strcat(filerespl,fileresu);
                   10600:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10601:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10602:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10603:   }
1.288     brouard  10604:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10605:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10606:   pstamp(ficrespl);
1.288     brouard  10607:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10608:   fprintf(ficrespl,"#Age ");
                   10609:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10610:   fprintf(ficrespl,"\n");
1.180     brouard  10611:   
1.219     brouard  10612:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10613: 
1.219     brouard  10614:   agebase=ageminpar;
                   10615:   agelim=agemaxpar;
1.180     brouard  10616: 
1.227     brouard  10617:   /* i1=pow(2,ncoveff); */
1.234     brouard  10618:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10619:   if (cptcovn < 1){i1=1;}
1.180     brouard  10620: 
1.238     brouard  10621:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10622:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10623:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10624:        continue;
1.235     brouard  10625: 
1.238     brouard  10626:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10627:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10628:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10629:       /* k=k+1; */
                   10630:       /* to clean */
                   10631:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10632:       fprintf(ficrespl,"#******");
                   10633:       printf("#******");
                   10634:       fprintf(ficlog,"#******");
                   10635:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10636:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10637:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10638:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10639:       }
                   10640:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10641:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10642:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10643:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10644:       }
                   10645:       fprintf(ficrespl,"******\n");
                   10646:       printf("******\n");
                   10647:       fprintf(ficlog,"******\n");
                   10648:       if(invalidvarcomb[k]){
                   10649:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10650:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10651:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10652:        continue;
                   10653:       }
1.219     brouard  10654: 
1.238     brouard  10655:       fprintf(ficrespl,"#Age ");
                   10656:       for(j=1;j<=cptcoveff;j++) {
                   10657:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10658:       }
                   10659:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10660:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10661:     
1.238     brouard  10662:       for (age=agebase; age<=agelim; age++){
                   10663:        /* for (age=agebase; age<=agebase; age++){ */
                   10664:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10665:        fprintf(ficrespl,"%.0f ",age );
                   10666:        for(j=1;j<=cptcoveff;j++)
                   10667:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10668:        tot=0.;
                   10669:        for(i=1; i<=nlstate;i++){
                   10670:          tot +=  prlim[i][i];
                   10671:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10672:        }
                   10673:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10674:       } /* Age */
                   10675:       /* was end of cptcod */
                   10676:     } /* cptcov */
                   10677:   } /* nres */
1.219     brouard  10678:   return 0;
1.180     brouard  10679: }
                   10680: 
1.218     brouard  10681: 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  10682:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10683:        
                   10684:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10685:    * at any age between ageminpar and agemaxpar
                   10686:         */
1.235     brouard  10687:   int i, j, k, i1, nres=0 ;
1.217     brouard  10688:   /* double ftolpl = 1.e-10; */
                   10689:   double age, agebase, agelim;
                   10690:   double tot;
1.218     brouard  10691:   /* double ***mobaverage; */
                   10692:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10693: 
                   10694:   strcpy(fileresplb,"PLB_");
                   10695:   strcat(fileresplb,fileresu);
                   10696:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10697:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10698:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10699:   }
1.288     brouard  10700:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10701:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10702:   pstamp(ficresplb);
1.288     brouard  10703:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10704:   fprintf(ficresplb,"#Age ");
                   10705:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10706:   fprintf(ficresplb,"\n");
                   10707:   
1.218     brouard  10708:   
                   10709:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10710:   
                   10711:   agebase=ageminpar;
                   10712:   agelim=agemaxpar;
                   10713:   
                   10714:   
1.227     brouard  10715:   i1=pow(2,cptcoveff);
1.218     brouard  10716:   if (cptcovn < 1){i1=1;}
1.227     brouard  10717:   
1.238     brouard  10718:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10719:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10720:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10721:        continue;
                   10722:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10723:       fprintf(ficresplb,"#******");
                   10724:       printf("#******");
                   10725:       fprintf(ficlog,"#******");
                   10726:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10727:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10728:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10729:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10730:       }
                   10731:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10732:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10733:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10734:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10735:       }
                   10736:       fprintf(ficresplb,"******\n");
                   10737:       printf("******\n");
                   10738:       fprintf(ficlog,"******\n");
                   10739:       if(invalidvarcomb[k]){
                   10740:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10741:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10742:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10743:        continue;
                   10744:       }
1.218     brouard  10745:     
1.238     brouard  10746:       fprintf(ficresplb,"#Age ");
                   10747:       for(j=1;j<=cptcoveff;j++) {
                   10748:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10749:       }
                   10750:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10751:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10752:     
                   10753:     
1.238     brouard  10754:       for (age=agebase; age<=agelim; age++){
                   10755:        /* for (age=agebase; age<=agebase; age++){ */
                   10756:        if(mobilavproj > 0){
                   10757:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10758:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10759:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10760:        }else if (mobilavproj == 0){
                   10761:          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);
                   10762:          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);
                   10763:          exit(1);
                   10764:        }else{
                   10765:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10766:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10767:          /* printf("TOTOT\n"); */
                   10768:           /* exit(1); */
1.238     brouard  10769:        }
                   10770:        fprintf(ficresplb,"%.0f ",age );
                   10771:        for(j=1;j<=cptcoveff;j++)
                   10772:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10773:        tot=0.;
                   10774:        for(i=1; i<=nlstate;i++){
                   10775:          tot +=  bprlim[i][i];
                   10776:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10777:        }
                   10778:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10779:       } /* Age */
                   10780:       /* was end of cptcod */
1.255     brouard  10781:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10782:     } /* end of any combination */
                   10783:   } /* end of nres */  
1.218     brouard  10784:   /* hBijx(p, bage, fage); */
                   10785:   /* fclose(ficrespijb); */
                   10786:   
                   10787:   return 0;
1.217     brouard  10788: }
1.218     brouard  10789:  
1.180     brouard  10790: int hPijx(double *p, int bage, int fage){
                   10791:     /*------------- h Pij x at various ages ------------*/
                   10792: 
                   10793:   int stepsize;
                   10794:   int agelim;
                   10795:   int hstepm;
                   10796:   int nhstepm;
1.235     brouard  10797:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10798: 
                   10799:   double agedeb;
                   10800:   double ***p3mat;
                   10801: 
1.201     brouard  10802:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10803:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10804:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10805:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10806:     }
                   10807:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10808:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10809:   
                   10810:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10811:     /*if (stepm<=24) stepsize=2;*/
                   10812: 
                   10813:     agelim=AGESUP;
                   10814:     hstepm=stepsize*YEARM; /* Every year of age */
                   10815:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10816:                
1.180     brouard  10817:     /* hstepm=1;   aff par mois*/
                   10818:     pstamp(ficrespij);
                   10819:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10820:     i1= pow(2,cptcoveff);
1.218     brouard  10821:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10822:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10823:                /*      k=k+1;  */
1.235     brouard  10824:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10825:     for(k=1; k<=i1;k++){
1.253     brouard  10826:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10827:        continue;
1.183     brouard  10828:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10829:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10830:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10831:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10832:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10833:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10834:       }
1.183     brouard  10835:       fprintf(ficrespij,"******\n");
                   10836:       
                   10837:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10838:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10839:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10840:        
                   10841:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10842:        
1.183     brouard  10843:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10844:        oldm=oldms;savm=savms;
1.235     brouard  10845:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10846:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10847:        for(i=1; i<=nlstate;i++)
                   10848:          for(j=1; j<=nlstate+ndeath;j++)
                   10849:            fprintf(ficrespij," %1d-%1d",i,j);
                   10850:        fprintf(ficrespij,"\n");
                   10851:        for (h=0; h<=nhstepm; h++){
                   10852:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10853:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10854:          for(i=1; i<=nlstate;i++)
                   10855:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10856:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10857:          fprintf(ficrespij,"\n");
                   10858:        }
1.183     brouard  10859:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10860:        fprintf(ficrespij,"\n");
                   10861:       }
1.180     brouard  10862:       /*}*/
                   10863:     }
1.218     brouard  10864:     return 0;
1.180     brouard  10865: }
1.218     brouard  10866:  
                   10867:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10868:     /*------------- h Bij x at various ages ------------*/
                   10869: 
                   10870:   int stepsize;
1.218     brouard  10871:   /* int agelim; */
                   10872:        int ageminl;
1.217     brouard  10873:   int hstepm;
                   10874:   int nhstepm;
1.238     brouard  10875:   int h, i, i1, j, k, nres;
1.218     brouard  10876:        
1.217     brouard  10877:   double agedeb;
                   10878:   double ***p3mat;
1.218     brouard  10879:        
                   10880:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10881:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10882:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10883:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10884:   }
                   10885:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10886:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10887:   
                   10888:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10889:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10890:   
1.218     brouard  10891:   /* agelim=AGESUP; */
1.289     brouard  10892:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10893:   hstepm=stepsize*YEARM; /* Every year of age */
                   10894:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10895:   
                   10896:   /* hstepm=1;   aff par mois*/
                   10897:   pstamp(ficrespijb);
1.255     brouard  10898:   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  10899:   i1= pow(2,cptcoveff);
1.218     brouard  10900:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10901:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10902:   /*   k=k+1;  */
1.238     brouard  10903:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10904:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10905:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10906:        continue;
                   10907:       fprintf(ficrespijb,"\n#****** ");
                   10908:       for(j=1;j<=cptcoveff;j++)
                   10909:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10910:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10911:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10912:       }
                   10913:       fprintf(ficrespijb,"******\n");
1.264     brouard  10914:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10915:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10916:        continue;
                   10917:       }
                   10918:       
                   10919:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10920:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10921:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  10922:        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 */
                   10923:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  10924:        
                   10925:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10926:        
1.266     brouard  10927:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10928:        /* and memory limitations if stepm is small */
                   10929: 
1.238     brouard  10930:        /* oldm=oldms;savm=savms; */
                   10931:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10932:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10933:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10934:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10935:        for(i=1; i<=nlstate;i++)
                   10936:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10937:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10938:        fprintf(ficrespijb,"\n");
1.238     brouard  10939:        for (h=0; h<=nhstepm; h++){
                   10940:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10941:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10942:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10943:          for(i=1; i<=nlstate;i++)
                   10944:            for(j=1; j<=nlstate+ndeath;j++)
                   10945:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10946:          fprintf(ficrespijb,"\n");
                   10947:        }
                   10948:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10949:        fprintf(ficrespijb,"\n");
                   10950:       } /* end age deb */
                   10951:     } /* end combination */
                   10952:   } /* end nres */
1.218     brouard  10953:   return 0;
                   10954:  } /*  hBijx */
1.217     brouard  10955: 
1.180     brouard  10956: 
1.136     brouard  10957: /***********************************************/
                   10958: /**************** Main Program *****************/
                   10959: /***********************************************/
                   10960: 
                   10961: int main(int argc, char *argv[])
                   10962: {
                   10963: #ifdef GSL
                   10964:   const gsl_multimin_fminimizer_type *T;
                   10965:   size_t iteri = 0, it;
                   10966:   int rval = GSL_CONTINUE;
                   10967:   int status = GSL_SUCCESS;
                   10968:   double ssval;
                   10969: #endif
                   10970:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10971:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10972:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10973:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10974:   int jj, ll, li, lj, lk;
1.136     brouard  10975:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10976:   int num_filled;
1.136     brouard  10977:   int itimes;
                   10978:   int NDIM=2;
                   10979:   int vpopbased=0;
1.235     brouard  10980:   int nres=0;
1.258     brouard  10981:   int endishere=0;
1.277     brouard  10982:   int noffset=0;
1.274     brouard  10983:   int ncurrv=0; /* Temporary variable */
                   10984:   
1.164     brouard  10985:   char ca[32], cb[32];
1.136     brouard  10986:   /*  FILE *fichtm; *//* Html File */
                   10987:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10988:   struct stat info;
1.191     brouard  10989:   double agedeb=0.;
1.194     brouard  10990: 
                   10991:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10992:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10993: 
1.165     brouard  10994:   double fret;
1.191     brouard  10995:   double dum=0.; /* Dummy variable */
1.136     brouard  10996:   double ***p3mat;
1.218     brouard  10997:   /* double ***mobaverage; */
1.164     brouard  10998: 
                   10999:   char line[MAXLINE];
1.197     brouard  11000:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11001: 
1.234     brouard  11002:   char  modeltemp[MAXLINE];
1.230     brouard  11003:   char resultline[MAXLINE];
                   11004:   
1.136     brouard  11005:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11006:   char *tok, *val; /* pathtot */
1.290     brouard  11007:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11008:   int c,  h , cpt, c2;
1.191     brouard  11009:   int jl=0;
                   11010:   int i1, j1, jk, stepsize=0;
1.194     brouard  11011:   int count=0;
                   11012: 
1.164     brouard  11013:   int *tab; 
1.136     brouard  11014:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11015:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11016:   /* double anprojf, mprojf, jprojf; */
                   11017:   /* double jintmean,mintmean,aintmean;   */
                   11018:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11019:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11020:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11021:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11022:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11023:   int mobilav=0,popforecast=0;
1.191     brouard  11024:   int hstepm=0, nhstepm=0;
1.136     brouard  11025:   int agemortsup;
                   11026:   float  sumlpop=0.;
                   11027:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11028:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11029: 
1.191     brouard  11030:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11031:   double ftolpl=FTOL;
                   11032:   double **prlim;
1.217     brouard  11033:   double **bprlim;
1.136     brouard  11034:   double ***param; /* Matrix of parameters */
1.251     brouard  11035:   double ***paramstart; /* Matrix of starting parameter values */
                   11036:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11037:   double **matcov; /* Matrix of covariance */
1.203     brouard  11038:   double **hess; /* Hessian matrix */
1.136     brouard  11039:   double ***delti3; /* Scale */
                   11040:   double *delti; /* Scale */
                   11041:   double ***eij, ***vareij;
                   11042:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11043: 
1.136     brouard  11044:   double *epj, vepp;
1.164     brouard  11045: 
1.273     brouard  11046:   double dateprev1, dateprev2;
1.296     brouard  11047:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11048:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11049: 
1.217     brouard  11050: 
1.136     brouard  11051:   double **ximort;
1.145     brouard  11052:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11053:   int *dcwave;
                   11054: 
1.164     brouard  11055:   char z[1]="c";
1.136     brouard  11056: 
                   11057:   /*char  *strt;*/
                   11058:   char strtend[80];
1.126     brouard  11059: 
1.164     brouard  11060: 
1.126     brouard  11061: /*   setlocale (LC_ALL, ""); */
                   11062: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11063: /*   textdomain (PACKAGE); */
                   11064: /*   setlocale (LC_CTYPE, ""); */
                   11065: /*   setlocale (LC_MESSAGES, ""); */
                   11066: 
                   11067:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11068:   rstart_time = time(NULL);  
                   11069:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11070:   start_time = *localtime(&rstart_time);
1.126     brouard  11071:   curr_time=start_time;
1.157     brouard  11072:   /*tml = *localtime(&start_time.tm_sec);*/
                   11073:   /* strcpy(strstart,asctime(&tml)); */
                   11074:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11075: 
                   11076: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11077: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11078: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11079: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11080: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11081: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11082: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11083: /*   strt=asctime(&tmg); */
                   11084: /*   printf("Time(after) =%s",strstart);  */
                   11085: /*  (void) time (&time_value);
                   11086: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11087: *  tm = *localtime(&time_value);
                   11088: *  strstart=asctime(&tm);
                   11089: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11090: */
                   11091: 
                   11092:   nberr=0; /* Number of errors and warnings */
                   11093:   nbwarn=0;
1.184     brouard  11094: #ifdef WIN32
                   11095:   _getcwd(pathcd, size);
                   11096: #else
1.126     brouard  11097:   getcwd(pathcd, size);
1.184     brouard  11098: #endif
1.191     brouard  11099:   syscompilerinfo(0);
1.196     brouard  11100:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11101:   if(argc <=1){
                   11102:     printf("\nEnter the parameter file name: ");
1.205     brouard  11103:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11104:       printf("ERROR Empty parameter file name\n");
                   11105:       goto end;
                   11106:     }
1.126     brouard  11107:     i=strlen(pathr);
                   11108:     if(pathr[i-1]=='\n')
                   11109:       pathr[i-1]='\0';
1.156     brouard  11110:     i=strlen(pathr);
1.205     brouard  11111:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11112:       pathr[i-1]='\0';
1.205     brouard  11113:     }
                   11114:     i=strlen(pathr);
                   11115:     if( i==0 ){
                   11116:       printf("ERROR Empty parameter file name\n");
                   11117:       goto end;
                   11118:     }
                   11119:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11120:       printf("Pathr |%s|\n",pathr);
                   11121:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11122:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11123:       strcpy (pathtot, val);
                   11124:       if(pathr[0] == '\0') break; /* Dirty */
                   11125:     }
                   11126:   }
1.281     brouard  11127:   else if (argc<=2){
                   11128:     strcpy(pathtot,argv[1]);
                   11129:   }
1.126     brouard  11130:   else{
                   11131:     strcpy(pathtot,argv[1]);
1.281     brouard  11132:     strcpy(z,argv[2]);
                   11133:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11134:   }
                   11135:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11136:   /*cygwin_split_path(pathtot,path,optionfile);
                   11137:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11138:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11139: 
                   11140:   /* Split argv[0], imach program to get pathimach */
                   11141:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11142:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11143:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11144:  /*   strcpy(pathimach,argv[0]); */
                   11145:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11146:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11147:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11148: #ifdef WIN32
                   11149:   _chdir(path); /* Can be a relative path */
                   11150:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11151: #else
1.126     brouard  11152:   chdir(path); /* Can be a relative path */
1.184     brouard  11153:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11154: #endif
                   11155:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11156:   strcpy(command,"mkdir ");
                   11157:   strcat(command,optionfilefiname);
                   11158:   if((outcmd=system(command)) != 0){
1.169     brouard  11159:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11160:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11161:     /* fclose(ficlog); */
                   11162: /*     exit(1); */
                   11163:   }
                   11164: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11165: /*     perror("mkdir"); */
                   11166: /*   } */
                   11167: 
                   11168:   /*-------- arguments in the command line --------*/
                   11169: 
1.186     brouard  11170:   /* Main Log file */
1.126     brouard  11171:   strcat(filelog, optionfilefiname);
                   11172:   strcat(filelog,".log");    /* */
                   11173:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11174:     printf("Problem with logfile %s\n",filelog);
                   11175:     goto end;
                   11176:   }
                   11177:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11178:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11179:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11180:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11181:  path=%s \n\
                   11182:  optionfile=%s\n\
                   11183:  optionfilext=%s\n\
1.156     brouard  11184:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11185: 
1.197     brouard  11186:   syscompilerinfo(1);
1.167     brouard  11187: 
1.126     brouard  11188:   printf("Local time (at start):%s",strstart);
                   11189:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11190:   fflush(ficlog);
                   11191: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11192: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11193: 
                   11194:   /* */
                   11195:   strcpy(fileres,"r");
                   11196:   strcat(fileres, optionfilefiname);
1.201     brouard  11197:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11198:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11199:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11200: 
1.186     brouard  11201:   /* Main ---------arguments file --------*/
1.126     brouard  11202: 
                   11203:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11204:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11205:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11206:     fflush(ficlog);
1.149     brouard  11207:     /* goto end; */
                   11208:     exit(70); 
1.126     brouard  11209:   }
                   11210: 
                   11211:   strcpy(filereso,"o");
1.201     brouard  11212:   strcat(filereso,fileresu);
1.126     brouard  11213:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11214:     printf("Problem with Output resultfile: %s\n", filereso);
                   11215:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11216:     fflush(ficlog);
                   11217:     goto end;
                   11218:   }
1.278     brouard  11219:       /*-------- Rewriting parameter file ----------*/
                   11220:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11221:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11222:   strcat(rfileres,".");    /* */
                   11223:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11224:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11225:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11226:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11227:     fflush(ficlog);
                   11228:     goto end;
                   11229:   }
                   11230:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11231: 
1.278     brouard  11232:                                      
1.126     brouard  11233:   /* Reads comments: lines beginning with '#' */
                   11234:   numlinepar=0;
1.277     brouard  11235:   /* Is it a BOM UTF-8 Windows file? */
                   11236:   /* First parameter line */
1.197     brouard  11237:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11238:     noffset=0;
                   11239:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11240:     {
                   11241:       noffset=noffset+3;
                   11242:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11243:     }
1.302     brouard  11244: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11245:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11246:     {
                   11247:       noffset=noffset+2;
                   11248:       printf("# File is an UTF16BE BOM file\n");
                   11249:     }
                   11250:     else if( line[0] == 0 && line[1] == 0)
                   11251:     {
                   11252:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11253:        noffset=noffset+4;
                   11254:        printf("# File is an UTF16BE BOM file\n");
                   11255:       }
                   11256:     } else{
                   11257:       ;/*printf(" Not a BOM file\n");*/
                   11258:     }
                   11259:   
1.197     brouard  11260:     /* If line starts with a # it is a comment */
1.277     brouard  11261:     if (line[noffset] == '#') {
1.197     brouard  11262:       numlinepar++;
                   11263:       fputs(line,stdout);
                   11264:       fputs(line,ficparo);
1.278     brouard  11265:       fputs(line,ficres);
1.197     brouard  11266:       fputs(line,ficlog);
                   11267:       continue;
                   11268:     }else
                   11269:       break;
                   11270:   }
                   11271:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11272:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11273:     if (num_filled != 5) {
                   11274:       printf("Should be 5 parameters\n");
1.283     brouard  11275:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11276:     }
1.126     brouard  11277:     numlinepar++;
1.197     brouard  11278:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11279:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11280:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11281:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11282:   }
                   11283:   /* Second parameter line */
                   11284:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11285:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11286:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11287:     if (line[0] == '#') {
                   11288:       numlinepar++;
1.283     brouard  11289:       printf("%s",line);
                   11290:       fprintf(ficres,"%s",line);
                   11291:       fprintf(ficparo,"%s",line);
                   11292:       fprintf(ficlog,"%s",line);
1.197     brouard  11293:       continue;
                   11294:     }else
                   11295:       break;
                   11296:   }
1.223     brouard  11297:   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", \
                   11298:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11299:     if (num_filled != 11) {
                   11300:       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  11301:       printf("but line=%s\n",line);
1.283     brouard  11302:       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");
                   11303:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11304:     }
1.286     brouard  11305:     if( lastpass > maxwav){
                   11306:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11307:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11308:       fflush(ficlog);
                   11309:       goto end;
                   11310:     }
                   11311:       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  11312:     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  11313:     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  11314:     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  11315:   }
1.203     brouard  11316:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11317:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11318:   /* Third parameter line */
                   11319:   while(fgets(line, MAXLINE, ficpar)) {
                   11320:     /* If line starts with a # it is a comment */
                   11321:     if (line[0] == '#') {
                   11322:       numlinepar++;
1.283     brouard  11323:       printf("%s",line);
                   11324:       fprintf(ficres,"%s",line);
                   11325:       fprintf(ficparo,"%s",line);
                   11326:       fprintf(ficlog,"%s",line);
1.197     brouard  11327:       continue;
                   11328:     }else
                   11329:       break;
                   11330:   }
1.201     brouard  11331:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11332:     if (num_filled != 1){
1.302     brouard  11333:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11334:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11335:       model[0]='\0';
                   11336:       goto end;
                   11337:     }
                   11338:     else{
                   11339:       if (model[0]=='+'){
                   11340:        for(i=1; i<=strlen(model);i++)
                   11341:          modeltemp[i-1]=model[i];
1.201     brouard  11342:        strcpy(model,modeltemp); 
1.197     brouard  11343:       }
                   11344:     }
1.199     brouard  11345:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11346:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11347:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11348:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11349:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11350:   }
                   11351:   /* 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); */
                   11352:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11353:   /* 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  11354:   /* 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); */
                   11355:   /* 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  11356:   fflush(ficlog);
1.190     brouard  11357:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11358:   if(model[0]=='#'){
1.279     brouard  11359:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11360:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11361:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11362:     if(mle != -1){
1.279     brouard  11363:       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  11364:       exit(1);
                   11365:     }
                   11366:   }
1.126     brouard  11367:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11368:     ungetc(c,ficpar);
                   11369:     fgets(line, MAXLINE, ficpar);
                   11370:     numlinepar++;
1.195     brouard  11371:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11372:       z[0]=line[1];
                   11373:     }
                   11374:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11375:     fputs(line, stdout);
                   11376:     //puts(line);
1.126     brouard  11377:     fputs(line,ficparo);
                   11378:     fputs(line,ficlog);
                   11379:   }
                   11380:   ungetc(c,ficpar);
                   11381: 
                   11382:    
1.290     brouard  11383:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11384:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11385:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11386:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11387:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11388:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11389:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11390:   */
                   11391:   if (strlen(model)>1) 
1.187     brouard  11392:     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  11393:   else
1.187     brouard  11394:     ncovmodel=2; /* Constant and age */
1.133     brouard  11395:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11396:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11397:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11398:     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);
                   11399:     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);
                   11400:     fflush(stdout);
                   11401:     fclose (ficlog);
                   11402:     goto end;
                   11403:   }
1.126     brouard  11404:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11405:   delti=delti3[1][1];
                   11406:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11407:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11408: /* We could also provide initial parameters values giving by simple logistic regression 
                   11409:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11410:       /* for(i=1;i<nlstate;i++){ */
                   11411:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11412:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11413:       /* } */
1.126     brouard  11414:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11415:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11416:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11417:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11418:     fclose (ficparo);
                   11419:     fclose (ficlog);
                   11420:     goto end;
                   11421:     exit(0);
1.220     brouard  11422:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11423:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11424:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11425:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11426:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11427:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11428:     hess=matrix(1,npar,1,npar);
1.220     brouard  11429:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11430:     /* Read guessed parameters */
1.126     brouard  11431:     /* Reads comments: lines beginning with '#' */
                   11432:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11433:       ungetc(c,ficpar);
                   11434:       fgets(line, MAXLINE, ficpar);
                   11435:       numlinepar++;
1.141     brouard  11436:       fputs(line,stdout);
1.126     brouard  11437:       fputs(line,ficparo);
                   11438:       fputs(line,ficlog);
                   11439:     }
                   11440:     ungetc(c,ficpar);
                   11441:     
                   11442:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11443:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11444:     for(i=1; i <=nlstate; i++){
1.234     brouard  11445:       j=0;
1.126     brouard  11446:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11447:        if(jj==i) continue;
                   11448:        j++;
1.292     brouard  11449:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11450:          ungetc(c,ficpar);
                   11451:          fgets(line, MAXLINE, ficpar);
                   11452:          numlinepar++;
                   11453:          fputs(line,stdout);
                   11454:          fputs(line,ficparo);
                   11455:          fputs(line,ficlog);
                   11456:        }
                   11457:        ungetc(c,ficpar);
1.234     brouard  11458:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11459:        if ((i1 != i) || (j1 != jj)){
                   11460:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11461: It might be a problem of design; if ncovcol and the model are correct\n \
                   11462: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11463:          exit(1);
                   11464:        }
                   11465:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11466:        if(mle==1)
                   11467:          printf("%1d%1d",i,jj);
                   11468:        fprintf(ficlog,"%1d%1d",i,jj);
                   11469:        for(k=1; k<=ncovmodel;k++){
                   11470:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11471:          if(mle==1){
                   11472:            printf(" %lf",param[i][j][k]);
                   11473:            fprintf(ficlog," %lf",param[i][j][k]);
                   11474:          }
                   11475:          else
                   11476:            fprintf(ficlog," %lf",param[i][j][k]);
                   11477:          fprintf(ficparo," %lf",param[i][j][k]);
                   11478:        }
                   11479:        fscanf(ficpar,"\n");
                   11480:        numlinepar++;
                   11481:        if(mle==1)
                   11482:          printf("\n");
                   11483:        fprintf(ficlog,"\n");
                   11484:        fprintf(ficparo,"\n");
1.126     brouard  11485:       }
                   11486:     }  
                   11487:     fflush(ficlog);
1.234     brouard  11488:     
1.251     brouard  11489:     /* Reads parameters values */
1.126     brouard  11490:     p=param[1][1];
1.251     brouard  11491:     pstart=paramstart[1][1];
1.126     brouard  11492:     
                   11493:     /* Reads comments: lines beginning with '#' */
                   11494:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11495:       ungetc(c,ficpar);
                   11496:       fgets(line, MAXLINE, ficpar);
                   11497:       numlinepar++;
1.141     brouard  11498:       fputs(line,stdout);
1.126     brouard  11499:       fputs(line,ficparo);
                   11500:       fputs(line,ficlog);
                   11501:     }
                   11502:     ungetc(c,ficpar);
                   11503: 
                   11504:     for(i=1; i <=nlstate; i++){
                   11505:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11506:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11507:        if ( (i1-i) * (j1-j) != 0){
                   11508:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11509:          exit(1);
                   11510:        }
                   11511:        printf("%1d%1d",i,j);
                   11512:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11513:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11514:        for(k=1; k<=ncovmodel;k++){
                   11515:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11516:          printf(" %le",delti3[i][j][k]);
                   11517:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11518:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11519:        }
                   11520:        fscanf(ficpar,"\n");
                   11521:        numlinepar++;
                   11522:        printf("\n");
                   11523:        fprintf(ficparo,"\n");
                   11524:        fprintf(ficlog,"\n");
1.126     brouard  11525:       }
                   11526:     }
                   11527:     fflush(ficlog);
1.234     brouard  11528:     
1.145     brouard  11529:     /* Reads covariance matrix */
1.126     brouard  11530:     delti=delti3[1][1];
1.220     brouard  11531:                
                   11532:                
1.126     brouard  11533:     /* 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  11534:                
1.126     brouard  11535:     /* Reads comments: lines beginning with '#' */
                   11536:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11537:       ungetc(c,ficpar);
                   11538:       fgets(line, MAXLINE, ficpar);
                   11539:       numlinepar++;
1.141     brouard  11540:       fputs(line,stdout);
1.126     brouard  11541:       fputs(line,ficparo);
                   11542:       fputs(line,ficlog);
                   11543:     }
                   11544:     ungetc(c,ficpar);
1.220     brouard  11545:                
1.126     brouard  11546:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11547:     hess=matrix(1,npar,1,npar);
1.131     brouard  11548:     for(i=1; i <=npar; i++)
                   11549:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11550:                
1.194     brouard  11551:     /* Scans npar lines */
1.126     brouard  11552:     for(i=1; i <=npar; i++){
1.226     brouard  11553:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11554:       if(count != 3){
1.226     brouard  11555:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11556: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11557: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11558:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11559: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11560: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11561:        exit(1);
1.220     brouard  11562:       }else{
1.226     brouard  11563:        if(mle==1)
                   11564:          printf("%1d%1d%d",i1,j1,jk);
                   11565:       }
                   11566:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11567:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11568:       for(j=1; j <=i; j++){
1.226     brouard  11569:        fscanf(ficpar," %le",&matcov[i][j]);
                   11570:        if(mle==1){
                   11571:          printf(" %.5le",matcov[i][j]);
                   11572:        }
                   11573:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11574:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11575:       }
                   11576:       fscanf(ficpar,"\n");
                   11577:       numlinepar++;
                   11578:       if(mle==1)
1.220     brouard  11579:                                printf("\n");
1.126     brouard  11580:       fprintf(ficlog,"\n");
                   11581:       fprintf(ficparo,"\n");
                   11582:     }
1.194     brouard  11583:     /* End of read covariance matrix npar lines */
1.126     brouard  11584:     for(i=1; i <=npar; i++)
                   11585:       for(j=i+1;j<=npar;j++)
1.226     brouard  11586:        matcov[i][j]=matcov[j][i];
1.126     brouard  11587:     
                   11588:     if(mle==1)
                   11589:       printf("\n");
                   11590:     fprintf(ficlog,"\n");
                   11591:     
                   11592:     fflush(ficlog);
                   11593:     
                   11594:   }    /* End of mle != -3 */
1.218     brouard  11595:   
1.186     brouard  11596:   /*  Main data
                   11597:    */
1.290     brouard  11598:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11599:   /* num=lvector(1,n); */
                   11600:   /* moisnais=vector(1,n); */
                   11601:   /* annais=vector(1,n); */
                   11602:   /* moisdc=vector(1,n); */
                   11603:   /* andc=vector(1,n); */
                   11604:   /* weight=vector(1,n); */
                   11605:   /* agedc=vector(1,n); */
                   11606:   /* cod=ivector(1,n); */
                   11607:   /* for(i=1;i<=n;i++){ */
                   11608:   num=lvector(firstobs,lastobs);
                   11609:   moisnais=vector(firstobs,lastobs);
                   11610:   annais=vector(firstobs,lastobs);
                   11611:   moisdc=vector(firstobs,lastobs);
                   11612:   andc=vector(firstobs,lastobs);
                   11613:   weight=vector(firstobs,lastobs);
                   11614:   agedc=vector(firstobs,lastobs);
                   11615:   cod=ivector(firstobs,lastobs);
                   11616:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11617:     num[i]=0;
                   11618:     moisnais[i]=0;
                   11619:     annais[i]=0;
                   11620:     moisdc[i]=0;
                   11621:     andc[i]=0;
                   11622:     agedc[i]=0;
                   11623:     cod[i]=0;
                   11624:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11625:   }
1.290     brouard  11626:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11627:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11628:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11629:   tab=ivector(1,NCOVMAX);
1.144     brouard  11630:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11631:   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  11632: 
1.136     brouard  11633:   /* Reads data from file datafile */
                   11634:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11635:     goto end;
                   11636: 
                   11637:   /* Calculation of the number of parameters from char model */
1.234     brouard  11638:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11639:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11640:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11641:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11642:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11643:   */
                   11644:   
                   11645:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11646:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11647:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11648:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11649:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11650:   TvarF=ivector(1,NCOVMAX); /*  */
                   11651:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11652:   TvarV=ivector(1,NCOVMAX); /*  */
                   11653:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11654:   TvarA=ivector(1,NCOVMAX); /*  */
                   11655:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11656:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11657:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11658:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11659:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11660:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11661:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11662:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11663:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11664: 
1.230     brouard  11665:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11666:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11667:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11668:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11669:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11670:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11671:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11672:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11673:   */
                   11674:   /* For model-covariate k tells which data-covariate to use but
                   11675:     because this model-covariate is a construction we invent a new column
                   11676:     ncovcol + k1
                   11677:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11678:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11679:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11680:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11681:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11682:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11683:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11684:   */
1.145     brouard  11685:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11686:   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  11687:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11688:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11689:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11690:                         4 covariates (3 plus signs)
                   11691:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11692:                      */  
1.230     brouard  11693:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11694:                                * individual dummy, fixed or varying:
                   11695:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11696:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11697:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11698:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11699:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11700:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11701:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11702:                                * individual quantitative, fixed or varying:
                   11703:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11704:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11705:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11706: /* Main decodemodel */
                   11707: 
1.187     brouard  11708: 
1.223     brouard  11709:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11710:     goto end;
                   11711: 
1.137     brouard  11712:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11713:     nbwarn++;
                   11714:     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); 
                   11715:     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); 
                   11716:   }
1.136     brouard  11717:     /*  if(mle==1){*/
1.137     brouard  11718:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11719:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11720:   }
                   11721: 
                   11722:     /*-calculation of age at interview from date of interview and age at death -*/
                   11723:   agev=matrix(1,maxwav,1,imx);
                   11724: 
                   11725:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11726:     goto end;
                   11727: 
1.126     brouard  11728: 
1.136     brouard  11729:   agegomp=(int)agemin;
1.290     brouard  11730:   free_vector(moisnais,firstobs,lastobs);
                   11731:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11732:   /* free_matrix(mint,1,maxwav,1,n);
                   11733:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11734:   /* free_vector(moisdc,1,n); */
                   11735:   /* free_vector(andc,1,n); */
1.145     brouard  11736:   /* */
                   11737:   
1.126     brouard  11738:   wav=ivector(1,imx);
1.214     brouard  11739:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11740:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11741:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11742:   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.*/
                   11743:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11744:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11745:    
                   11746:   /* Concatenates waves */
1.214     brouard  11747:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11748:      Death is a valid wave (if date is known).
                   11749:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11750:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11751:      and mw[mi+1][i]. dh depends on stepm.
                   11752:   */
                   11753: 
1.126     brouard  11754:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11755:   /* Concatenates waves */
1.145     brouard  11756:  
1.290     brouard  11757:   free_vector(moisdc,firstobs,lastobs);
                   11758:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11759: 
1.126     brouard  11760:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11761:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11762:   ncodemax[1]=1;
1.145     brouard  11763:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11764:   cptcoveff=0;
1.220     brouard  11765:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11766:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11767:   }
                   11768:   
                   11769:   ncovcombmax=pow(2,cptcoveff);
                   11770:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11771:   for(i=1;i<ncovcombmax;i++)
                   11772:     invalidvarcomb[i]=0;
                   11773:   
1.211     brouard  11774:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11775:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11776:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11777:   
1.200     brouard  11778:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11779:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11780:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11781:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11782:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11783:    * (currently 0 or 1) in the data.
                   11784:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11785:    * corresponding modality (h,j).
                   11786:    */
                   11787: 
1.145     brouard  11788:   h=0;
                   11789:   /*if (cptcovn > 0) */
1.126     brouard  11790:   m=pow(2,cptcoveff);
                   11791:  
1.144     brouard  11792:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11793:           * For k=4 covariates, h goes from 1 to m=2**k
                   11794:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11795:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11796:           *     h\k   1     2     3     4
1.143     brouard  11797:           *______________________________  
                   11798:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11799:           *     2     2     1     1     1
                   11800:           *     3 i=2 1     2     1     1
                   11801:           *     4     2     2     1     1
                   11802:           *     5 i=3 1 i=2 1     2     1
                   11803:           *     6     2     1     2     1
                   11804:           *     7 i=4 1     2     2     1
                   11805:           *     8     2     2     2     1
1.197     brouard  11806:           *     9 i=5 1 i=3 1 i=2 1     2
                   11807:           *    10     2     1     1     2
                   11808:           *    11 i=6 1     2     1     2
                   11809:           *    12     2     2     1     2
                   11810:           *    13 i=7 1 i=4 1     2     2    
                   11811:           *    14     2     1     2     2
                   11812:           *    15 i=8 1     2     2     2
                   11813:           *    16     2     2     2     2
1.143     brouard  11814:           */
1.212     brouard  11815:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11816:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11817:      * and the value of each covariate?
                   11818:      * V1=1, V2=1, V3=2, V4=1 ?
                   11819:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11820:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11821:      * In order to get the real value in the data, we use nbcode
                   11822:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11823:      * We are keeping this crazy system in order to be able (in the future?) 
                   11824:      * to have more than 2 values (0 or 1) for a covariate.
                   11825:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11826:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11827:      *              bbbbbbbb
                   11828:      *              76543210     
                   11829:      *   h-1        00000101 (6-1=5)
1.219     brouard  11830:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11831:      *           &
                   11832:      *     1        00000001 (1)
1.219     brouard  11833:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11834:      *          +1= 00000001 =1 
1.211     brouard  11835:      *
                   11836:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11837:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11838:      *    >>k'            11
                   11839:      *          &   00000001
                   11840:      *            = 00000001
                   11841:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11842:      * Reverse h=6 and m=16?
                   11843:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11844:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11845:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11846:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11847:      * V3=decodtabm(14,3,2**4)=2
                   11848:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11849:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11850:      *          &1 000000001
                   11851:      *           = 000000001
                   11852:      *         +1= 000000010 =2
                   11853:      *                  2211
                   11854:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11855:      *                  V3=2
1.220     brouard  11856:                 * codtabm and decodtabm are identical
1.211     brouard  11857:      */
                   11858: 
1.145     brouard  11859: 
                   11860:  free_ivector(Ndum,-1,NCOVMAX);
                   11861: 
                   11862: 
1.126     brouard  11863:     
1.186     brouard  11864:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11865:   strcpy(optionfilegnuplot,optionfilefiname);
                   11866:   if(mle==-3)
1.201     brouard  11867:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11868:   strcat(optionfilegnuplot,".gp");
                   11869: 
                   11870:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11871:     printf("Problem with file %s",optionfilegnuplot);
                   11872:   }
                   11873:   else{
1.204     brouard  11874:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11875:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11876:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11877:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11878:   }
                   11879:   /*  fclose(ficgp);*/
1.186     brouard  11880: 
                   11881: 
                   11882:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11883: 
                   11884:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11885:   if(mle==-3)
1.201     brouard  11886:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11887:   strcat(optionfilehtm,".htm");
                   11888:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11889:     printf("Problem with %s \n",optionfilehtm);
                   11890:     exit(0);
1.126     brouard  11891:   }
                   11892: 
                   11893:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11894:   strcat(optionfilehtmcov,"-cov.htm");
                   11895:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11896:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11897:   }
                   11898:   else{
                   11899:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11900: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11901: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11902:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11903:   }
                   11904: 
1.213     brouard  11905:   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  11906: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11907: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11908: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11909: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11910: \n\
                   11911: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11912:  <ul><li><h4>Parameter files</h4>\n\
                   11913:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11914:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11915:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11916:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11917:  - Date and time at start: %s</ul>\n",\
                   11918:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11919:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11920:          fileres,fileres,\
                   11921:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11922:   fflush(fichtm);
                   11923: 
                   11924:   strcpy(pathr,path);
                   11925:   strcat(pathr,optionfilefiname);
1.184     brouard  11926: #ifdef WIN32
                   11927:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11928: #else
1.126     brouard  11929:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11930: #endif
                   11931:          
1.126     brouard  11932:   
1.220     brouard  11933:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11934:                 and for any valid combination of covariates
1.126     brouard  11935:      and prints on file fileres'p'. */
1.251     brouard  11936:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11937:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11938: 
                   11939:   fprintf(fichtm,"\n");
1.286     brouard  11940:   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  11941:          ftol, stepm);
                   11942:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11943:   ncurrv=1;
                   11944:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11945:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11946:   ncurrv=i;
                   11947:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11948:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11949:   ncurrv=i;
                   11950:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11951:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11952:   ncurrv=i;
                   11953:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11954:   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", \
                   11955:           nlstate, ndeath, maxwav, mle, weightopt);
                   11956: 
                   11957:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11958: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11959: 
                   11960:   
                   11961:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11962: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11963: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11964:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11965:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11966:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11967:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11968:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11969:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11970: 
1.126     brouard  11971:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11972:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11973:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11974: 
                   11975:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11976:   /* For mortality only */
1.126     brouard  11977:   if (mle==-3){
1.136     brouard  11978:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11979:     for(i=1;i<=NDIM;i++)
                   11980:       for(j=1;j<=NDIM;j++)
                   11981:        ximort[i][j]=0.;
1.186     brouard  11982:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11983:     cens=ivector(firstobs,lastobs);
                   11984:     ageexmed=vector(firstobs,lastobs);
                   11985:     agecens=vector(firstobs,lastobs);
                   11986:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11987:                
1.126     brouard  11988:     for (i=1; i<=imx; i++){
                   11989:       dcwave[i]=-1;
                   11990:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11991:        if (s[m][i]>nlstate) {
                   11992:          dcwave[i]=m;
                   11993:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11994:          break;
                   11995:        }
1.126     brouard  11996:     }
1.226     brouard  11997:     
1.126     brouard  11998:     for (i=1; i<=imx; i++) {
                   11999:       if (wav[i]>0){
1.226     brouard  12000:        ageexmed[i]=agev[mw[1][i]][i];
                   12001:        j=wav[i];
                   12002:        agecens[i]=1.; 
                   12003:        
                   12004:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12005:          agecens[i]=agev[mw[j][i]][i];
                   12006:          cens[i]= 1;
                   12007:        }else if (ageexmed[i]< 1) 
                   12008:          cens[i]= -1;
                   12009:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12010:          cens[i]=0 ;
1.126     brouard  12011:       }
                   12012:       else cens[i]=-1;
                   12013:     }
                   12014:     
                   12015:     for (i=1;i<=NDIM;i++) {
                   12016:       for (j=1;j<=NDIM;j++)
1.226     brouard  12017:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12018:     }
                   12019:     
1.302     brouard  12020:     p[1]=0.0268; p[NDIM]=0.083;
                   12021:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12022:     
                   12023:     
1.136     brouard  12024: #ifdef GSL
                   12025:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12026: #else
1.126     brouard  12027:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12028: #endif
1.201     brouard  12029:     strcpy(filerespow,"POW-MORT_"); 
                   12030:     strcat(filerespow,fileresu);
1.126     brouard  12031:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12032:       printf("Problem with resultfile: %s\n", filerespow);
                   12033:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12034:     }
1.136     brouard  12035: #ifdef GSL
                   12036:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12037: #else
1.126     brouard  12038:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12039: #endif
1.126     brouard  12040:     /*  for (i=1;i<=nlstate;i++)
                   12041:        for(j=1;j<=nlstate+ndeath;j++)
                   12042:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12043:     */
                   12044:     fprintf(ficrespow,"\n");
1.136     brouard  12045: #ifdef GSL
                   12046:     /* gsl starts here */ 
                   12047:     T = gsl_multimin_fminimizer_nmsimplex;
                   12048:     gsl_multimin_fminimizer *sfm = NULL;
                   12049:     gsl_vector *ss, *x;
                   12050:     gsl_multimin_function minex_func;
                   12051: 
                   12052:     /* Initial vertex size vector */
                   12053:     ss = gsl_vector_alloc (NDIM);
                   12054:     
                   12055:     if (ss == NULL){
                   12056:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12057:     }
                   12058:     /* Set all step sizes to 1 */
                   12059:     gsl_vector_set_all (ss, 0.001);
                   12060: 
                   12061:     /* Starting point */
1.126     brouard  12062:     
1.136     brouard  12063:     x = gsl_vector_alloc (NDIM);
                   12064:     
                   12065:     if (x == NULL){
                   12066:       gsl_vector_free(ss);
                   12067:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12068:     }
                   12069:   
                   12070:     /* Initialize method and iterate */
                   12071:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12072:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12073:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12074:     gsl_vector_set(x, 0, p[1]);
                   12075:     gsl_vector_set(x, 1, p[2]);
                   12076: 
                   12077:     minex_func.f = &gompertz_f;
                   12078:     minex_func.n = NDIM;
                   12079:     minex_func.params = (void *)&p; /* ??? */
                   12080:     
                   12081:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12082:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12083:     
                   12084:     printf("Iterations beginning .....\n\n");
                   12085:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12086: 
                   12087:     iteri=0;
                   12088:     while (rval == GSL_CONTINUE){
                   12089:       iteri++;
                   12090:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12091:       
                   12092:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12093:       fflush(0);
                   12094:       
                   12095:       if (status) 
                   12096:         break;
                   12097:       
                   12098:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12099:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12100:       
                   12101:       if (rval == GSL_SUCCESS)
                   12102:         printf ("converged to a local maximum at\n");
                   12103:       
                   12104:       printf("%5d ", iteri);
                   12105:       for (it = 0; it < NDIM; it++){
                   12106:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12107:       }
                   12108:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12109:     }
                   12110:     
                   12111:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12112:     
                   12113:     gsl_vector_free(x); /* initial values */
                   12114:     gsl_vector_free(ss); /* inital step size */
                   12115:     for (it=0; it<NDIM; it++){
                   12116:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12117:       fprintf(ficrespow," %.12lf", p[it]);
                   12118:     }
                   12119:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12120: #endif
                   12121: #ifdef POWELL
                   12122:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12123: #endif  
1.126     brouard  12124:     fclose(ficrespow);
                   12125:     
1.203     brouard  12126:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12127: 
                   12128:     for(i=1; i <=NDIM; i++)
                   12129:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12130:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12131:     
                   12132:     printf("\nCovariance matrix\n ");
1.203     brouard  12133:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12134:     for(i=1; i <=NDIM; i++) {
                   12135:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12136:                                printf("%f ",matcov[i][j]);
                   12137:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12138:       }
1.203     brouard  12139:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12140:     }
                   12141:     
                   12142:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12143:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12144:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12145:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12146:     }
1.302     brouard  12147:     lsurv=vector(agegomp,AGESUP);
                   12148:     lpop=vector(agegomp,AGESUP);
                   12149:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12150:     lsurv[agegomp]=100000;
                   12151:     
                   12152:     for (k=agegomp;k<=AGESUP;k++) {
                   12153:       agemortsup=k;
                   12154:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12155:     }
                   12156:     
                   12157:     for (k=agegomp;k<agemortsup;k++)
                   12158:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12159:     
                   12160:     for (k=agegomp;k<agemortsup;k++){
                   12161:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12162:       sumlpop=sumlpop+lpop[k];
                   12163:     }
                   12164:     
                   12165:     tpop[agegomp]=sumlpop;
                   12166:     for (k=agegomp;k<(agemortsup-3);k++){
                   12167:       /*  tpop[k+1]=2;*/
                   12168:       tpop[k+1]=tpop[k]-lpop[k];
                   12169:     }
                   12170:     
                   12171:     
                   12172:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12173:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12174:       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]);
                   12175:     
                   12176:     
                   12177:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12178:                ageminpar=50;
                   12179:                agemaxpar=100;
1.194     brouard  12180:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12181:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12182: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12183: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12184:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12185: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12186: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12187:     }else{
                   12188:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12189:                        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  12190:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12191:                }
1.201     brouard  12192:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12193:                     stepm, weightopt,\
                   12194:                     model,imx,p,matcov,agemortsup);
                   12195:     
1.302     brouard  12196:     free_vector(lsurv,agegomp,AGESUP);
                   12197:     free_vector(lpop,agegomp,AGESUP);
                   12198:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12199:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12200:     free_ivector(dcwave,firstobs,lastobs);
                   12201:     free_vector(agecens,firstobs,lastobs);
                   12202:     free_vector(ageexmed,firstobs,lastobs);
                   12203:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12204: #ifdef GSL
1.136     brouard  12205: #endif
1.186     brouard  12206:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12207:   /* Standard  */
                   12208:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12209:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12210:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12211:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12212:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12213:     for (k=1; k<=npar;k++)
                   12214:       printf(" %d %8.5f",k,p[k]);
                   12215:     printf("\n");
1.205     brouard  12216:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12217:       /* mlikeli uses func not funcone */
1.247     brouard  12218:       /* for(i=1;i<nlstate;i++){ */
                   12219:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12220:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12221:       /* } */
1.205     brouard  12222:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12223:     }
                   12224:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12225:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12226:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12227:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12228:     }
                   12229:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12230:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12231:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12232:     for (k=1; k<=npar;k++)
                   12233:       printf(" %d %8.5f",k,p[k]);
                   12234:     printf("\n");
                   12235:     
                   12236:     /*--------- results files --------------*/
1.283     brouard  12237:     /* 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  12238:     
                   12239:     
                   12240:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12241:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12242:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12243:     for(i=1,jk=1; i <=nlstate; i++){
                   12244:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12245:        if (k != i) {
                   12246:          printf("%d%d ",i,k);
                   12247:          fprintf(ficlog,"%d%d ",i,k);
                   12248:          fprintf(ficres,"%1d%1d ",i,k);
                   12249:          for(j=1; j <=ncovmodel; j++){
                   12250:            printf("%12.7f ",p[jk]);
                   12251:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12252:            fprintf(ficres,"%12.7f ",p[jk]);
                   12253:            jk++; 
                   12254:          }
                   12255:          printf("\n");
                   12256:          fprintf(ficlog,"\n");
                   12257:          fprintf(ficres,"\n");
                   12258:        }
1.126     brouard  12259:       }
                   12260:     }
1.203     brouard  12261:     if(mle != 0){
                   12262:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12263:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12264:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12265:       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");
                   12266:       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");
                   12267:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12268:        for(k=1; k <=(nlstate+ndeath); k++){
                   12269:          if (k != i) {
                   12270:            printf("%d%d ",i,k);
                   12271:            fprintf(ficlog,"%d%d ",i,k);
                   12272:            for(j=1; j <=ncovmodel; j++){
                   12273:              printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   12274:              fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   12275:              jk++; 
                   12276:            }
                   12277:            printf("\n");
                   12278:            fprintf(ficlog,"\n");
                   12279:          }
                   12280:        }
1.193     brouard  12281:       }
1.203     brouard  12282:     } /* end of hesscov and Wald tests */
1.225     brouard  12283:     
1.203     brouard  12284:     /*  */
1.126     brouard  12285:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12286:     printf("# Scales (for hessian or gradient estimation)\n");
                   12287:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12288:     for(i=1,jk=1; i <=nlstate; i++){
                   12289:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12290:        if (j!=i) {
                   12291:          fprintf(ficres,"%1d%1d",i,j);
                   12292:          printf("%1d%1d",i,j);
                   12293:          fprintf(ficlog,"%1d%1d",i,j);
                   12294:          for(k=1; k<=ncovmodel;k++){
                   12295:            printf(" %.5e",delti[jk]);
                   12296:            fprintf(ficlog," %.5e",delti[jk]);
                   12297:            fprintf(ficres," %.5e",delti[jk]);
                   12298:            jk++;
                   12299:          }
                   12300:          printf("\n");
                   12301:          fprintf(ficlog,"\n");
                   12302:          fprintf(ficres,"\n");
                   12303:        }
1.126     brouard  12304:       }
                   12305:     }
                   12306:     
                   12307:     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  12308:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12309:       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");
                   12310:     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");
                   12311:     /* # 121 Var(a12)\n\ */
                   12312:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12313:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12314:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12315:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12316:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12317:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12318:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12319:     
                   12320:     
                   12321:     /* Just to have a covariance matrix which will be more understandable
                   12322:        even is we still don't want to manage dictionary of variables
                   12323:     */
                   12324:     for(itimes=1;itimes<=2;itimes++){
                   12325:       jj=0;
                   12326:       for(i=1; i <=nlstate; i++){
1.225     brouard  12327:        for(j=1; j <=nlstate+ndeath; j++){
                   12328:          if(j==i) continue;
                   12329:          for(k=1; k<=ncovmodel;k++){
                   12330:            jj++;
                   12331:            ca[0]= k+'a'-1;ca[1]='\0';
                   12332:            if(itimes==1){
                   12333:              if(mle>=1)
                   12334:                printf("#%1d%1d%d",i,j,k);
                   12335:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12336:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12337:            }else{
                   12338:              if(mle>=1)
                   12339:                printf("%1d%1d%d",i,j,k);
                   12340:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12341:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12342:            }
                   12343:            ll=0;
                   12344:            for(li=1;li <=nlstate; li++){
                   12345:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12346:                if(lj==li) continue;
                   12347:                for(lk=1;lk<=ncovmodel;lk++){
                   12348:                  ll++;
                   12349:                  if(ll<=jj){
                   12350:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12351:                    if(ll<jj){
                   12352:                      if(itimes==1){
                   12353:                        if(mle>=1)
                   12354:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12355:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12356:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12357:                      }else{
                   12358:                        if(mle>=1)
                   12359:                          printf(" %.5e",matcov[jj][ll]); 
                   12360:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12361:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12362:                      }
                   12363:                    }else{
                   12364:                      if(itimes==1){
                   12365:                        if(mle>=1)
                   12366:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12367:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12368:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12369:                      }else{
                   12370:                        if(mle>=1)
                   12371:                          printf(" %.7e",matcov[jj][ll]); 
                   12372:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12373:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12374:                      }
                   12375:                    }
                   12376:                  }
                   12377:                } /* end lk */
                   12378:              } /* end lj */
                   12379:            } /* end li */
                   12380:            if(mle>=1)
                   12381:              printf("\n");
                   12382:            fprintf(ficlog,"\n");
                   12383:            fprintf(ficres,"\n");
                   12384:            numlinepar++;
                   12385:          } /* end k*/
                   12386:        } /*end j */
1.126     brouard  12387:       } /* end i */
                   12388:     } /* end itimes */
                   12389:     
                   12390:     fflush(ficlog);
                   12391:     fflush(ficres);
1.225     brouard  12392:     while(fgets(line, MAXLINE, ficpar)) {
                   12393:       /* If line starts with a # it is a comment */
                   12394:       if (line[0] == '#') {
                   12395:        numlinepar++;
                   12396:        fputs(line,stdout);
                   12397:        fputs(line,ficparo);
                   12398:        fputs(line,ficlog);
1.299     brouard  12399:        fputs(line,ficres);
1.225     brouard  12400:        continue;
                   12401:       }else
                   12402:        break;
                   12403:     }
                   12404:     
1.209     brouard  12405:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12406:     /*   ungetc(c,ficpar); */
                   12407:     /*   fgets(line, MAXLINE, ficpar); */
                   12408:     /*   fputs(line,stdout); */
                   12409:     /*   fputs(line,ficparo); */
                   12410:     /* } */
                   12411:     /* ungetc(c,ficpar); */
1.126     brouard  12412:     
                   12413:     estepm=0;
1.209     brouard  12414:     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  12415:       
                   12416:       if (num_filled != 6) {
                   12417:        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);
                   12418:        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);
                   12419:        goto end;
                   12420:       }
                   12421:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12422:     }
                   12423:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12424:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12425:     
1.209     brouard  12426:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12427:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12428:     if (fage <= 2) {
                   12429:       bage = ageminpar;
                   12430:       fage = agemaxpar;
                   12431:     }
                   12432:     
                   12433:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12434:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12435:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12436:                
1.186     brouard  12437:     /* Other stuffs, more or less useful */    
1.254     brouard  12438:     while(fgets(line, MAXLINE, ficpar)) {
                   12439:       /* If line starts with a # it is a comment */
                   12440:       if (line[0] == '#') {
                   12441:        numlinepar++;
                   12442:        fputs(line,stdout);
                   12443:        fputs(line,ficparo);
                   12444:        fputs(line,ficlog);
1.299     brouard  12445:        fputs(line,ficres);
1.254     brouard  12446:        continue;
                   12447:       }else
                   12448:        break;
                   12449:     }
                   12450: 
                   12451:     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){
                   12452:       
                   12453:       if (num_filled != 7) {
                   12454:        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);
                   12455:        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);
                   12456:        goto end;
                   12457:       }
                   12458:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12459:       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);
                   12460:       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);
                   12461:       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  12462:     }
1.254     brouard  12463: 
                   12464:     while(fgets(line, MAXLINE, ficpar)) {
                   12465:       /* If line starts with a # it is a comment */
                   12466:       if (line[0] == '#') {
                   12467:        numlinepar++;
                   12468:        fputs(line,stdout);
                   12469:        fputs(line,ficparo);
                   12470:        fputs(line,ficlog);
1.299     brouard  12471:        fputs(line,ficres);
1.254     brouard  12472:        continue;
                   12473:       }else
                   12474:        break;
1.126     brouard  12475:     }
                   12476:     
                   12477:     
                   12478:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12479:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12480:     
1.254     brouard  12481:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12482:       if (num_filled != 1) {
                   12483:        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);
                   12484:        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);
                   12485:        goto end;
                   12486:       }
                   12487:       printf("pop_based=%d\n",popbased);
                   12488:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12489:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12490:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12491:     }
                   12492:      
1.258     brouard  12493:     /* Results */
1.307     brouard  12494:     endishere=0;
1.258     brouard  12495:     nresult=0;
1.308     brouard  12496:     parameterline=0;
1.258     brouard  12497:     do{
                   12498:       if(!fgets(line, MAXLINE, ficpar)){
                   12499:        endishere=1;
1.308     brouard  12500:        parameterline=15;
1.258     brouard  12501:       }else if (line[0] == '#') {
                   12502:        /* If line starts with a # it is a comment */
1.254     brouard  12503:        numlinepar++;
                   12504:        fputs(line,stdout);
                   12505:        fputs(line,ficparo);
                   12506:        fputs(line,ficlog);
1.299     brouard  12507:        fputs(line,ficres);
1.254     brouard  12508:        continue;
1.258     brouard  12509:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12510:        parameterline=11;
1.296     brouard  12511:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12512:        parameterline=12;
1.307     brouard  12513:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  12514:        parameterline=13;
1.307     brouard  12515:       }
1.258     brouard  12516:       else{
                   12517:        parameterline=14;
1.254     brouard  12518:       }
1.308     brouard  12519:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  12520:       case 11:
1.296     brouard  12521:        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)){
                   12522:                  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  12523:          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);
                   12524:          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);
                   12525:          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);
                   12526:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12527:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12528:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12529:           prvforecast = 1;
                   12530:        } 
                   12531:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  12532:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12533:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12534:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12535:           prvforecast = 2;
                   12536:        }
                   12537:        else {
                   12538:          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);
                   12539:          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);
                   12540:          goto end;
1.258     brouard  12541:        }
1.254     brouard  12542:        break;
1.258     brouard  12543:       case 12:
1.296     brouard  12544:        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)){
                   12545:           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);
                   12546:          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);
                   12547:          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);
                   12548:          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);
                   12549:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12550:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12551:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12552:           prvbackcast = 1;
                   12553:        } 
                   12554:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  12555:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12556:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12557:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12558:           prvbackcast = 2;
                   12559:        }
                   12560:        else {
                   12561:          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);
                   12562:          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);
                   12563:          goto end;
1.258     brouard  12564:        }
1.230     brouard  12565:        break;
1.258     brouard  12566:       case 13:
1.307     brouard  12567:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   12568:        nresult++; /* Sum of resultlines */
                   12569:        printf("Result %d: result:%s\n",nresult, resultline);
                   12570:        if(nresult > MAXRESULTLINES){
                   12571:          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. ",MAXRESULTLINES,nresult,rfileres);
                   12572:          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. ",MAXRESULTLINES,nresult,rfileres);
                   12573:          goto end;
                   12574:        }
1.310     brouard  12575:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  12576:          fprintf(ficparo,"result: %s\n",resultline);
                   12577:          fprintf(ficres,"result: %s\n",resultline);
                   12578:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  12579:        } else
                   12580:          goto end;
1.307     brouard  12581:        break;
                   12582:       case 14:
                   12583:        printf("Error: Unknown command '%s'\n",line);
                   12584:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  12585:        if(line[0] == ' ' || line[0] == '\n'){
                   12586:          printf("It should not be an empty line '%s'\n",line);
                   12587:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   12588:        }         
1.307     brouard  12589:        if(ncovmodel >=2 && nresult==0 ){
                   12590:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   12591:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12592:        }
1.307     brouard  12593:        /* goto end; */
                   12594:        break;
1.308     brouard  12595:       case 15:
                   12596:        printf("End of resultlines.\n");
                   12597:        fprintf(ficlog,"End of resultlines.\n");
                   12598:        break;
                   12599:       default: /* parameterline =0 */
1.307     brouard  12600:        nresult=1;
                   12601:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  12602:       } /* End switch parameterline */
                   12603:     }while(endishere==0); /* End do */
1.126     brouard  12604:     
1.230     brouard  12605:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12606:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12607:     
                   12608:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12609:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12610:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12611: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12612: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12613:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12614: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12615: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12616:     }else{
1.270     brouard  12617:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12618:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12619:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12620:       if(prvforecast==1){
                   12621:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12622:         jprojd=jproj1;
                   12623:         mprojd=mproj1;
                   12624:         anprojd=anproj1;
                   12625:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12626:         jprojf=jproj2;
                   12627:         mprojf=mproj2;
                   12628:         anprojf=anproj2;
                   12629:       } else if(prvforecast == 2){
                   12630:         dateprojd=dateintmean;
                   12631:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12632:         dateprojf=dateintmean+yrfproj;
                   12633:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12634:       }
                   12635:       if(prvbackcast==1){
                   12636:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12637:         jbackd=jback1;
                   12638:         mbackd=mback1;
                   12639:         anbackd=anback1;
                   12640:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12641:         jbackf=jback2;
                   12642:         mbackf=mback2;
                   12643:         anbackf=anback2;
                   12644:       } else if(prvbackcast == 2){
                   12645:         datebackd=dateintmean;
                   12646:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12647:         datebackf=dateintmean-yrbproj;
                   12648:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12649:       }
                   12650:       
                   12651:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12652:     }
                   12653:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12654:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12655:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12656:                
1.225     brouard  12657:     /*------------ free_vector  -------------*/
                   12658:     /*  chdir(path); */
1.220     brouard  12659:                
1.215     brouard  12660:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12661:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12662:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12663:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12664:     free_lvector(num,firstobs,lastobs);
                   12665:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12666:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12667:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12668:     fclose(ficparo);
                   12669:     fclose(ficres);
1.220     brouard  12670:                
                   12671:                
1.186     brouard  12672:     /* Other results (useful)*/
1.220     brouard  12673:                
                   12674:                
1.126     brouard  12675:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12676:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12677:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12678:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12679:     fclose(ficrespl);
                   12680: 
                   12681:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12682:     /*#include "hpijx.h"*/
                   12683:     hPijx(p, bage, fage);
1.145     brouard  12684:     fclose(ficrespij);
1.227     brouard  12685:     
1.220     brouard  12686:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12687:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12688:     k=1;
1.126     brouard  12689:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12690:     
1.269     brouard  12691:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12692:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12693:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12694:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12695:        for(k=1;k<=ncovcombmax;k++)
                   12696:          probs[i][j][k]=0.;
1.269     brouard  12697:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12698:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12699:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12700:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12701:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12702:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12703:          for(k=1;k<=ncovcombmax;k++)
                   12704:            mobaverages[i][j][k]=0.;
1.219     brouard  12705:       mobaverage=mobaverages;
                   12706:       if (mobilav!=0) {
1.235     brouard  12707:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12708:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12709:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12710:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12711:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12712:        }
1.269     brouard  12713:       } else if (mobilavproj !=0) {
1.235     brouard  12714:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12715:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12716:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12717:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12718:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12719:        }
1.269     brouard  12720:       }else{
                   12721:        printf("Internal error moving average\n");
                   12722:        fflush(stdout);
                   12723:        exit(1);
1.219     brouard  12724:       }
                   12725:     }/* end if moving average */
1.227     brouard  12726:     
1.126     brouard  12727:     /*---------- Forecasting ------------------*/
1.296     brouard  12728:     if(prevfcast==1){ 
                   12729:       /*   /\*    if(stepm ==1){*\/ */
                   12730:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12731:       /*This done previously after freqsummary.*/
                   12732:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   12733:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   12734:       
                   12735:       /* } else if (prvforecast==2){ */
                   12736:       /*   /\*    if(stepm ==1){*\/ */
                   12737:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12738:       /* } */
                   12739:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   12740:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  12741:     }
1.269     brouard  12742: 
1.296     brouard  12743:     /* Prevbcasting */
                   12744:     if(prevbcast==1){
1.219     brouard  12745:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12746:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12747:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12748: 
                   12749:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12750: 
                   12751:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12752: 
1.219     brouard  12753:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12754:       fclose(ficresplb);
                   12755: 
1.222     brouard  12756:       hBijx(p, bage, fage, mobaverage);
                   12757:       fclose(ficrespijb);
1.219     brouard  12758: 
1.296     brouard  12759:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   12760:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   12761:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   12762:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   12763:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   12764:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   12765: 
                   12766:       
1.269     brouard  12767:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12768: 
                   12769:       
1.269     brouard  12770:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12771:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12772:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12773:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  12774:     }    /* end  Prevbcasting */
1.268     brouard  12775:  
1.186     brouard  12776:  
                   12777:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12778: 
1.215     brouard  12779:     free_ivector(wav,1,imx);
                   12780:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12781:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12782:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12783:                
                   12784:                
1.127     brouard  12785:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12786:                
1.201     brouard  12787:     strcpy(filerese,"E_");
                   12788:     strcat(filerese,fileresu);
1.126     brouard  12789:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12790:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12791:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12792:     }
1.208     brouard  12793:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12794:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12795: 
                   12796:     pstamp(ficreseij);
1.219     brouard  12797:                
1.235     brouard  12798:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12799:     if (cptcovn < 1){i1=1;}
                   12800:     
                   12801:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12802:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12803:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12804:        continue;
1.219     brouard  12805:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12806:       printf("\n#****** ");
1.225     brouard  12807:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12808:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12809:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12810:       }
                   12811:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12812:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12813:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12814:       }
                   12815:       fprintf(ficreseij,"******\n");
1.235     brouard  12816:       printf("******\n");
1.219     brouard  12817:       
                   12818:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12819:       oldm=oldms;savm=savms;
1.235     brouard  12820:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12821:       
1.219     brouard  12822:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12823:     }
                   12824:     fclose(ficreseij);
1.208     brouard  12825:     printf("done evsij\n");fflush(stdout);
                   12826:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12827: 
1.218     brouard  12828:                
1.227     brouard  12829:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12830:                
1.201     brouard  12831:     strcpy(filerest,"T_");
                   12832:     strcat(filerest,fileresu);
1.127     brouard  12833:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12834:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12835:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12836:     }
1.208     brouard  12837:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12838:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12839:     strcpy(fileresstde,"STDE_");
                   12840:     strcat(fileresstde,fileresu);
1.126     brouard  12841:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12842:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12843:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12844:     }
1.227     brouard  12845:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12846:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12847: 
1.201     brouard  12848:     strcpy(filerescve,"CVE_");
                   12849:     strcat(filerescve,fileresu);
1.126     brouard  12850:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12851:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12852:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12853:     }
1.227     brouard  12854:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12855:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12856: 
1.201     brouard  12857:     strcpy(fileresv,"V_");
                   12858:     strcat(fileresv,fileresu);
1.126     brouard  12859:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12860:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12861:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12862:     }
1.227     brouard  12863:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12864:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12865: 
1.235     brouard  12866:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12867:     if (cptcovn < 1){i1=1;}
                   12868:     
                   12869:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12870:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12871:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12872:        continue;
1.242     brouard  12873:       printf("\n#****** Result for:");
                   12874:       fprintf(ficrest,"\n#****** Result for:");
                   12875:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12876:       for(j=1;j<=cptcoveff;j++){ 
                   12877:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12878:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12879:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12880:       }
1.235     brouard  12881:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12882:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12883:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12884:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12885:       }        
1.208     brouard  12886:       fprintf(ficrest,"******\n");
1.227     brouard  12887:       fprintf(ficlog,"******\n");
                   12888:       printf("******\n");
1.208     brouard  12889:       
                   12890:       fprintf(ficresstdeij,"\n#****** ");
                   12891:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12892:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12893:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12894:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12895:       }
1.235     brouard  12896:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12897:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12898:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12899:       }        
1.208     brouard  12900:       fprintf(ficresstdeij,"******\n");
                   12901:       fprintf(ficrescveij,"******\n");
                   12902:       
                   12903:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12904:       /* pstamp(ficresvij); */
1.225     brouard  12905:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12906:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12907:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12908:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12909:       }        
1.208     brouard  12910:       fprintf(ficresvij,"******\n");
                   12911:       
                   12912:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12913:       oldm=oldms;savm=savms;
1.235     brouard  12914:       printf(" cvevsij ");
                   12915:       fprintf(ficlog, " cvevsij ");
                   12916:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12917:       printf(" end cvevsij \n ");
                   12918:       fprintf(ficlog, " end cvevsij \n ");
                   12919:       
                   12920:       /*
                   12921:        */
                   12922:       /* goto endfree; */
                   12923:       
                   12924:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12925:       pstamp(ficrest);
                   12926:       
1.269     brouard  12927:       epj=vector(1,nlstate+1);
1.208     brouard  12928:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12929:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12930:        cptcod= 0; /* To be deleted */
                   12931:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12932:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12933:        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  12934:        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 ");
                   12935:        if(vpopbased==1)
                   12936:          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);
                   12937:        else
1.288     brouard  12938:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12939:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12940:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12941:        fprintf(ficrest,"\n");
                   12942:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12943:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12944:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12945:        for(age=bage; age <=fage ;age++){
1.235     brouard  12946:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12947:          if (vpopbased==1) {
                   12948:            if(mobilav ==0){
                   12949:              for(i=1; i<=nlstate;i++)
                   12950:                prlim[i][i]=probs[(int)age][i][k];
                   12951:            }else{ /* mobilav */ 
                   12952:              for(i=1; i<=nlstate;i++)
                   12953:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12954:            }
                   12955:          }
1.219     brouard  12956:          
1.227     brouard  12957:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12958:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12959:          /* printf(" age %4.0f ",age); */
                   12960:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12961:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12962:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12963:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12964:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12965:            }
                   12966:            epj[nlstate+1] +=epj[j];
                   12967:          }
                   12968:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12969:          
1.227     brouard  12970:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12971:            for(j=1;j <=nlstate;j++)
                   12972:              vepp += vareij[i][j][(int)age];
                   12973:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12974:          for(j=1;j <=nlstate;j++){
                   12975:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12976:          }
                   12977:          fprintf(ficrest,"\n");
                   12978:        }
1.208     brouard  12979:       } /* End vpopbased */
1.269     brouard  12980:       free_vector(epj,1,nlstate+1);
1.208     brouard  12981:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12982:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12983:       printf("done selection\n");fflush(stdout);
                   12984:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12985:       
1.235     brouard  12986:     } /* End k selection */
1.227     brouard  12987: 
                   12988:     printf("done State-specific expectancies\n");fflush(stdout);
                   12989:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12990: 
1.288     brouard  12991:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12992:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12993: 
1.227     brouard  12994:     
1.290     brouard  12995:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12996:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12997:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12998:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12999:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13000:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13001:     free_ivector(tab,1,NCOVMAX);
                   13002:     fclose(ficresstdeij);
                   13003:     fclose(ficrescveij);
                   13004:     fclose(ficresvij);
                   13005:     fclose(ficrest);
                   13006:     fclose(ficpar);
                   13007:     
                   13008:     
1.126     brouard  13009:     /*---------- End : free ----------------*/
1.219     brouard  13010:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13011:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13012:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13013:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13014:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13015:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13016:   /* endfree:*/
                   13017:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13018:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13019:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13020:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13021:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13022:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13023:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13024:   free_matrix(matcov,1,npar,1,npar);
                   13025:   free_matrix(hess,1,npar,1,npar);
                   13026:   /*free_vector(delti,1,npar);*/
                   13027:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13028:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13029:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13030:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13031:   
                   13032:   free_ivector(ncodemax,1,NCOVMAX);
                   13033:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13034:   free_ivector(Dummy,-1,NCOVMAX);
                   13035:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13036:   free_ivector(DummyV,1,NCOVMAX);
                   13037:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13038:   free_ivector(Typevar,-1,NCOVMAX);
                   13039:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13040:   free_ivector(TvarsQ,1,NCOVMAX);
                   13041:   free_ivector(TvarsQind,1,NCOVMAX);
                   13042:   free_ivector(TvarsD,1,NCOVMAX);
                   13043:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13044:   free_ivector(TvarFD,1,NCOVMAX);
                   13045:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13046:   free_ivector(TvarF,1,NCOVMAX);
                   13047:   free_ivector(TvarFind,1,NCOVMAX);
                   13048:   free_ivector(TvarV,1,NCOVMAX);
                   13049:   free_ivector(TvarVind,1,NCOVMAX);
                   13050:   free_ivector(TvarA,1,NCOVMAX);
                   13051:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13052:   free_ivector(TvarFQ,1,NCOVMAX);
                   13053:   free_ivector(TvarFQind,1,NCOVMAX);
                   13054:   free_ivector(TvarVD,1,NCOVMAX);
                   13055:   free_ivector(TvarVDind,1,NCOVMAX);
                   13056:   free_ivector(TvarVQ,1,NCOVMAX);
                   13057:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13058:   free_ivector(Tvarsel,1,NCOVMAX);
                   13059:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13060:   free_ivector(Tposprod,1,NCOVMAX);
                   13061:   free_ivector(Tprod,1,NCOVMAX);
                   13062:   free_ivector(Tvaraff,1,NCOVMAX);
                   13063:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13064:   free_ivector(Tage,1,NCOVMAX);
                   13065:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13066:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13067:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13068:   
                   13069:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13070:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13071:   fflush(fichtm);
                   13072:   fflush(ficgp);
                   13073:   
1.227     brouard  13074:   
1.126     brouard  13075:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13076:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13077:     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  13078:   }else{
                   13079:     printf("End of Imach\n");
                   13080:     fprintf(ficlog,"End of Imach\n");
                   13081:   }
                   13082:   printf("See log file on %s\n",filelog);
                   13083:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13084:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13085:   rend_time = time(NULL);  
                   13086:   end_time = *localtime(&rend_time);
                   13087:   /* tml = *localtime(&end_time.tm_sec); */
                   13088:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13089:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13090:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13091:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13092:   
1.157     brouard  13093:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13094:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13095:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13096:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13097: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13098:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13099:   fclose(fichtm);
                   13100:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13101:   fclose(fichtmcov);
                   13102:   fclose(ficgp);
                   13103:   fclose(ficlog);
                   13104:   /*------ End -----------*/
1.227     brouard  13105:   
1.281     brouard  13106: 
                   13107: /* Executes gnuplot */
1.227     brouard  13108:   
                   13109:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13110: #ifdef WIN32
1.227     brouard  13111:   if (_chdir(pathcd) != 0)
                   13112:     printf("Can't move to directory %s!\n",path);
                   13113:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13114: #else
1.227     brouard  13115:     if(chdir(pathcd) != 0)
                   13116:       printf("Can't move to directory %s!\n", path);
                   13117:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13118: #endif 
1.126     brouard  13119:     printf("Current directory %s!\n",pathcd);
                   13120:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13121:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13122: #ifdef _WIN32
1.126     brouard  13123:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13124: #endif
                   13125:   if(!stat(plotcmd,&info)){
1.158     brouard  13126:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13127:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13128:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13129:     }else
                   13130:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13131: #ifdef __unix
1.126     brouard  13132:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13133:     if(!stat(plotcmd,&info)){
1.158     brouard  13134:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13135:     }else
                   13136:       strcpy(pplotcmd,plotcmd);
                   13137: #endif
                   13138:   }else
                   13139:     strcpy(pplotcmd,plotcmd);
                   13140:   
                   13141:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13142:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13143:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13144:   
1.126     brouard  13145:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13146:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13147:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13148:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13149:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13150:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13151:       strcpy(plotcmd,pplotcmd);
                   13152:     }
1.126     brouard  13153:   }
1.158     brouard  13154:   printf(" Successful, please wait...");
1.126     brouard  13155:   while (z[0] != 'q') {
                   13156:     /* chdir(path); */
1.154     brouard  13157:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13158:     scanf("%s",z);
                   13159: /*     if (z[0] == 'c') system("./imach"); */
                   13160:     if (z[0] == 'e') {
1.158     brouard  13161: #ifdef __APPLE__
1.152     brouard  13162:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13163: #elif __linux
                   13164:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13165: #else
1.152     brouard  13166:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13167: #endif
                   13168:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13169:       system(pplotcmd);
1.126     brouard  13170:     }
                   13171:     else if (z[0] == 'g') system(plotcmd);
                   13172:     else if (z[0] == 'q') exit(0);
                   13173:   }
1.227     brouard  13174: end:
1.126     brouard  13175:   while (z[0] != 'q') {
1.195     brouard  13176:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13177:     scanf("%s",z);
                   13178:   }
1.283     brouard  13179:   printf("End\n");
1.282     brouard  13180:   exit(0);
1.126     brouard  13181: }

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