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

1.317   ! brouard     1: /* $Id: imach.c,v 1.316 2022/05/11 15:11:31 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.317   ! brouard     4:   Revision 1.316  2022/05/11 15:11:31  brouard
        !             5:   Summary: r27
        !             6: 
1.316     brouard     7:   Revision 1.315  2022/05/11 15:06:32  brouard
                      8:   *** empty log message ***
                      9: 
1.315     brouard    10:   Revision 1.314  2022/04/13 17:43:09  brouard
                     11:   * imach.c (Module): Adding link to text data files
                     12: 
1.314     brouard    13:   Revision 1.313  2022/04/11 15:57:42  brouard
                     14:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     15: 
1.313     brouard    16:   Revision 1.312  2022/04/05 21:24:39  brouard
                     17:   *** empty log message ***
                     18: 
1.312     brouard    19:   Revision 1.311  2022/04/05 21:03:51  brouard
                     20:   Summary: Fixed quantitative covariates
                     21: 
                     22:          Fixed covariates (dummy or quantitative)
                     23:        with missing values have never been allowed but are ERRORS and
                     24:        program quits. Standard deviations of fixed covariates were
                     25:        wrongly computed. Mean and standard deviations of time varying
                     26:        covariates are still not computed.
                     27: 
1.311     brouard    28:   Revision 1.310  2022/03/17 08:45:53  brouard
                     29:   Summary: 99r25
                     30: 
                     31:   Improving detection of errors: result lines should be compatible with
                     32:   the model.
                     33: 
1.310     brouard    34:   Revision 1.309  2021/05/20 12:39:14  brouard
                     35:   Summary: Version 0.99r24
                     36: 
1.309     brouard    37:   Revision 1.308  2021/03/31 13:11:57  brouard
                     38:   Summary: Version 0.99r23
                     39: 
                     40: 
                     41:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     42: 
1.308     brouard    43:   Revision 1.307  2021/03/08 18:11:32  brouard
                     44:   Summary: 0.99r22 fixed bug on result:
                     45: 
1.307     brouard    46:   Revision 1.306  2021/02/20 15:44:02  brouard
                     47:   Summary: Version 0.99r21
                     48: 
                     49:   * imach.c (Module): Fix bug on quitting after result lines!
                     50:   (Module): Version 0.99r21
                     51: 
1.306     brouard    52:   Revision 1.305  2021/02/20 15:28:30  brouard
                     53:   * imach.c (Module): Fix bug on quitting after result lines!
                     54: 
1.305     brouard    55:   Revision 1.304  2021/02/12 11:34:20  brouard
                     56:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                     57: 
1.304     brouard    58:   Revision 1.303  2021/02/11 19:50:15  brouard
                     59:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                     60: 
1.303     brouard    61:   Revision 1.302  2020/02/22 21:00:05  brouard
                     62:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                     63:   and life table from the data without any state)
                     64: 
1.302     brouard    65:   Revision 1.301  2019/06/04 13:51:20  brouard
                     66:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                     67: 
1.301     brouard    68:   Revision 1.300  2019/05/22 19:09:45  brouard
                     69:   Summary: version 0.99r19 of May 2019
                     70: 
1.300     brouard    71:   Revision 1.299  2019/05/22 18:37:08  brouard
                     72:   Summary: Cleaned 0.99r19
                     73: 
1.299     brouard    74:   Revision 1.298  2019/05/22 18:19:56  brouard
                     75:   *** empty log message ***
                     76: 
1.298     brouard    77:   Revision 1.297  2019/05/22 17:56:10  brouard
                     78:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                     79: 
1.297     brouard    80:   Revision 1.296  2019/05/20 13:03:18  brouard
                     81:   Summary: Projection syntax simplified
                     82: 
                     83: 
                     84:   We can now start projections, forward or backward, from the mean date
                     85:   of inteviews up to or down to a number of years of projection:
                     86:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                     87:   or
                     88:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                     89:   or
                     90:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                     91:   or
                     92:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                     93: 
1.296     brouard    94:   Revision 1.295  2019/05/18 09:52:50  brouard
                     95:   Summary: doxygen tex bug
                     96: 
1.295     brouard    97:   Revision 1.294  2019/05/16 14:54:33  brouard
                     98:   Summary: There was some wrong lines added
                     99: 
1.294     brouard   100:   Revision 1.293  2019/05/09 15:17:34  brouard
                    101:   *** empty log message ***
                    102: 
1.293     brouard   103:   Revision 1.292  2019/05/09 14:17:20  brouard
                    104:   Summary: Some updates
                    105: 
1.292     brouard   106:   Revision 1.291  2019/05/09 13:44:18  brouard
                    107:   Summary: Before ncovmax
                    108: 
1.291     brouard   109:   Revision 1.290  2019/05/09 13:39:37  brouard
                    110:   Summary: 0.99r18 unlimited number of individuals
                    111: 
                    112:   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.
                    113: 
1.290     brouard   114:   Revision 1.289  2018/12/13 09:16:26  brouard
                    115:   Summary: Bug for young ages (<-30) will be in r17
                    116: 
1.289     brouard   117:   Revision 1.288  2018/05/02 20:58:27  brouard
                    118:   Summary: Some bugs fixed
                    119: 
1.288     brouard   120:   Revision 1.287  2018/05/01 17:57:25  brouard
                    121:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    122: 
1.287     brouard   123:   Revision 1.286  2018/04/27 14:27:04  brouard
                    124:   Summary: some minor bugs
                    125: 
1.286     brouard   126:   Revision 1.285  2018/04/21 21:02:16  brouard
                    127:   Summary: Some bugs fixed, valgrind tested
                    128: 
1.285     brouard   129:   Revision 1.284  2018/04/20 05:22:13  brouard
                    130:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    131: 
1.284     brouard   132:   Revision 1.283  2018/04/19 14:49:16  brouard
                    133:   Summary: Some minor bugs fixed
                    134: 
1.283     brouard   135:   Revision 1.282  2018/02/27 22:50:02  brouard
                    136:   *** empty log message ***
                    137: 
1.282     brouard   138:   Revision 1.281  2018/02/27 19:25:23  brouard
                    139:   Summary: Adding second argument for quitting
                    140: 
1.281     brouard   141:   Revision 1.280  2018/02/21 07:58:13  brouard
                    142:   Summary: 0.99r15
                    143: 
                    144:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    145: 
1.280     brouard   146:   Revision 1.279  2017/07/20 13:35:01  brouard
                    147:   Summary: temporary working
                    148: 
1.279     brouard   149:   Revision 1.278  2017/07/19 14:09:02  brouard
                    150:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    151: 
1.278     brouard   152:   Revision 1.277  2017/07/17 08:53:49  brouard
                    153:   Summary: BOM files can be read now
                    154: 
1.277     brouard   155:   Revision 1.276  2017/06/30 15:48:31  brouard
                    156:   Summary: Graphs improvements
                    157: 
1.276     brouard   158:   Revision 1.275  2017/06/30 13:39:33  brouard
                    159:   Summary: Saito's color
                    160: 
1.275     brouard   161:   Revision 1.274  2017/06/29 09:47:08  brouard
                    162:   Summary: Version 0.99r14
                    163: 
1.274     brouard   164:   Revision 1.273  2017/06/27 11:06:02  brouard
                    165:   Summary: More documentation on projections
                    166: 
1.273     brouard   167:   Revision 1.272  2017/06/27 10:22:40  brouard
                    168:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    169: 
1.272     brouard   170:   Revision 1.271  2017/06/27 10:17:50  brouard
                    171:   Summary: Some bug with rint
                    172: 
1.271     brouard   173:   Revision 1.270  2017/05/24 05:45:29  brouard
                    174:   *** empty log message ***
                    175: 
1.270     brouard   176:   Revision 1.269  2017/05/23 08:39:25  brouard
                    177:   Summary: Code into subroutine, cleanings
                    178: 
1.269     brouard   179:   Revision 1.268  2017/05/18 20:09:32  brouard
                    180:   Summary: backprojection and confidence intervals of backprevalence
                    181: 
1.268     brouard   182:   Revision 1.267  2017/05/13 10:25:05  brouard
                    183:   Summary: temporary save for backprojection
                    184: 
1.267     brouard   185:   Revision 1.266  2017/05/13 07:26:12  brouard
                    186:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    187: 
1.266     brouard   188:   Revision 1.265  2017/04/26 16:22:11  brouard
                    189:   Summary: imach 0.99r13 Some bugs fixed
                    190: 
1.265     brouard   191:   Revision 1.264  2017/04/26 06:01:29  brouard
                    192:   Summary: Labels in graphs
                    193: 
1.264     brouard   194:   Revision 1.263  2017/04/24 15:23:15  brouard
                    195:   Summary: to save
                    196: 
1.263     brouard   197:   Revision 1.262  2017/04/18 16:48:12  brouard
                    198:   *** empty log message ***
                    199: 
1.262     brouard   200:   Revision 1.261  2017/04/05 10:14:09  brouard
                    201:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    202: 
1.261     brouard   203:   Revision 1.260  2017/04/04 17:46:59  brouard
                    204:   Summary: Gnuplot indexations fixed (humm)
                    205: 
1.260     brouard   206:   Revision 1.259  2017/04/04 13:01:16  brouard
                    207:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    208: 
1.259     brouard   209:   Revision 1.258  2017/04/03 10:17:47  brouard
                    210:   Summary: Version 0.99r12
                    211: 
                    212:   Some cleanings, conformed with updated documentation.
                    213: 
1.258     brouard   214:   Revision 1.257  2017/03/29 16:53:30  brouard
                    215:   Summary: Temp
                    216: 
1.257     brouard   217:   Revision 1.256  2017/03/27 05:50:23  brouard
                    218:   Summary: Temporary
                    219: 
1.256     brouard   220:   Revision 1.255  2017/03/08 16:02:28  brouard
                    221:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    222: 
1.255     brouard   223:   Revision 1.254  2017/03/08 07:13:00  brouard
                    224:   Summary: Fixing data parameter line
                    225: 
1.254     brouard   226:   Revision 1.253  2016/12/15 11:59:41  brouard
                    227:   Summary: 0.99 in progress
                    228: 
1.253     brouard   229:   Revision 1.252  2016/09/15 21:15:37  brouard
                    230:   *** empty log message ***
                    231: 
1.252     brouard   232:   Revision 1.251  2016/09/15 15:01:13  brouard
                    233:   Summary: not working
                    234: 
1.251     brouard   235:   Revision 1.250  2016/09/08 16:07:27  brouard
                    236:   Summary: continue
                    237: 
1.250     brouard   238:   Revision 1.249  2016/09/07 17:14:18  brouard
                    239:   Summary: Starting values from frequencies
                    240: 
1.249     brouard   241:   Revision 1.248  2016/09/07 14:10:18  brouard
                    242:   *** empty log message ***
                    243: 
1.248     brouard   244:   Revision 1.247  2016/09/02 11:11:21  brouard
                    245:   *** empty log message ***
                    246: 
1.247     brouard   247:   Revision 1.246  2016/09/02 08:49:22  brouard
                    248:   *** empty log message ***
                    249: 
1.246     brouard   250:   Revision 1.245  2016/09/02 07:25:01  brouard
                    251:   *** empty log message ***
                    252: 
1.245     brouard   253:   Revision 1.244  2016/09/02 07:17:34  brouard
                    254:   *** empty log message ***
                    255: 
1.244     brouard   256:   Revision 1.243  2016/09/02 06:45:35  brouard
                    257:   *** empty log message ***
                    258: 
1.243     brouard   259:   Revision 1.242  2016/08/30 15:01:20  brouard
                    260:   Summary: Fixing a lots
                    261: 
1.242     brouard   262:   Revision 1.241  2016/08/29 17:17:25  brouard
                    263:   Summary: gnuplot problem in Back projection to fix
                    264: 
1.241     brouard   265:   Revision 1.240  2016/08/29 07:53:18  brouard
                    266:   Summary: Better
                    267: 
1.240     brouard   268:   Revision 1.239  2016/08/26 15:51:03  brouard
                    269:   Summary: Improvement in Powell output in order to copy and paste
                    270: 
                    271:   Author:
                    272: 
1.239     brouard   273:   Revision 1.238  2016/08/26 14:23:35  brouard
                    274:   Summary: Starting tests of 0.99
                    275: 
1.238     brouard   276:   Revision 1.237  2016/08/26 09:20:19  brouard
                    277:   Summary: to valgrind
                    278: 
1.237     brouard   279:   Revision 1.236  2016/08/25 10:50:18  brouard
                    280:   *** empty log message ***
                    281: 
1.236     brouard   282:   Revision 1.235  2016/08/25 06:59:23  brouard
                    283:   *** empty log message ***
                    284: 
1.235     brouard   285:   Revision 1.234  2016/08/23 16:51:20  brouard
                    286:   *** empty log message ***
                    287: 
1.234     brouard   288:   Revision 1.233  2016/08/23 07:40:50  brouard
                    289:   Summary: not working
                    290: 
1.233     brouard   291:   Revision 1.232  2016/08/22 14:20:21  brouard
                    292:   Summary: not working
                    293: 
1.232     brouard   294:   Revision 1.231  2016/08/22 07:17:15  brouard
                    295:   Summary: not working
                    296: 
1.231     brouard   297:   Revision 1.230  2016/08/22 06:55:53  brouard
                    298:   Summary: Not working
                    299: 
1.230     brouard   300:   Revision 1.229  2016/07/23 09:45:53  brouard
                    301:   Summary: Completing for func too
                    302: 
1.229     brouard   303:   Revision 1.228  2016/07/22 17:45:30  brouard
                    304:   Summary: Fixing some arrays, still debugging
                    305: 
1.227     brouard   306:   Revision 1.226  2016/07/12 18:42:34  brouard
                    307:   Summary: temp
                    308: 
1.226     brouard   309:   Revision 1.225  2016/07/12 08:40:03  brouard
                    310:   Summary: saving but not running
                    311: 
1.225     brouard   312:   Revision 1.224  2016/07/01 13:16:01  brouard
                    313:   Summary: Fixes
                    314: 
1.224     brouard   315:   Revision 1.223  2016/02/19 09:23:35  brouard
                    316:   Summary: temporary
                    317: 
1.223     brouard   318:   Revision 1.222  2016/02/17 08:14:50  brouard
                    319:   Summary: Probably last 0.98 stable version 0.98r6
                    320: 
1.222     brouard   321:   Revision 1.221  2016/02/15 23:35:36  brouard
                    322:   Summary: minor bug
                    323: 
1.220     brouard   324:   Revision 1.219  2016/02/15 00:48:12  brouard
                    325:   *** empty log message ***
                    326: 
1.219     brouard   327:   Revision 1.218  2016/02/12 11:29:23  brouard
                    328:   Summary: 0.99 Back projections
                    329: 
1.218     brouard   330:   Revision 1.217  2015/12/23 17:18:31  brouard
                    331:   Summary: Experimental backcast
                    332: 
1.217     brouard   333:   Revision 1.216  2015/12/18 17:32:11  brouard
                    334:   Summary: 0.98r4 Warning and status=-2
                    335: 
                    336:   Version 0.98r4 is now:
                    337:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    338:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    339:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    340: 
1.216     brouard   341:   Revision 1.215  2015/12/16 08:52:24  brouard
                    342:   Summary: 0.98r4 working
                    343: 
1.215     brouard   344:   Revision 1.214  2015/12/16 06:57:54  brouard
                    345:   Summary: temporary not working
                    346: 
1.214     brouard   347:   Revision 1.213  2015/12/11 18:22:17  brouard
                    348:   Summary: 0.98r4
                    349: 
1.213     brouard   350:   Revision 1.212  2015/11/21 12:47:24  brouard
                    351:   Summary: minor typo
                    352: 
1.212     brouard   353:   Revision 1.211  2015/11/21 12:41:11  brouard
                    354:   Summary: 0.98r3 with some graph of projected cross-sectional
                    355: 
                    356:   Author: Nicolas Brouard
                    357: 
1.211     brouard   358:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   359:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   360:   Summary: Adding ftolpl parameter
                    361:   Author: N Brouard
                    362: 
                    363:   We had difficulties to get smoothed confidence intervals. It was due
                    364:   to the period prevalence which wasn't computed accurately. The inner
                    365:   parameter ftolpl is now an outer parameter of the .imach parameter
                    366:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    367:   computation are long.
                    368: 
1.209     brouard   369:   Revision 1.208  2015/11/17 14:31:57  brouard
                    370:   Summary: temporary
                    371: 
1.208     brouard   372:   Revision 1.207  2015/10/27 17:36:57  brouard
                    373:   *** empty log message ***
                    374: 
1.207     brouard   375:   Revision 1.206  2015/10/24 07:14:11  brouard
                    376:   *** empty log message ***
                    377: 
1.206     brouard   378:   Revision 1.205  2015/10/23 15:50:53  brouard
                    379:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    380: 
1.205     brouard   381:   Revision 1.204  2015/10/01 16:20:26  brouard
                    382:   Summary: Some new graphs of contribution to likelihood
                    383: 
1.204     brouard   384:   Revision 1.203  2015/09/30 17:45:14  brouard
                    385:   Summary: looking at better estimation of the hessian
                    386: 
                    387:   Also a better criteria for convergence to the period prevalence And
                    388:   therefore adding the number of years needed to converge. (The
                    389:   prevalence in any alive state shold sum to one
                    390: 
1.203     brouard   391:   Revision 1.202  2015/09/22 19:45:16  brouard
                    392:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    393: 
1.202     brouard   394:   Revision 1.201  2015/09/15 17:34:58  brouard
                    395:   Summary: 0.98r0
                    396: 
                    397:   - Some new graphs like suvival functions
                    398:   - Some bugs fixed like model=1+age+V2.
                    399: 
1.201     brouard   400:   Revision 1.200  2015/09/09 16:53:55  brouard
                    401:   Summary: Big bug thanks to Flavia
                    402: 
                    403:   Even model=1+age+V2. did not work anymore
                    404: 
1.200     brouard   405:   Revision 1.199  2015/09/07 14:09:23  brouard
                    406:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    407: 
1.199     brouard   408:   Revision 1.198  2015/09/03 07:14:39  brouard
                    409:   Summary: 0.98q5 Flavia
                    410: 
1.198     brouard   411:   Revision 1.197  2015/09/01 18:24:39  brouard
                    412:   *** empty log message ***
                    413: 
1.197     brouard   414:   Revision 1.196  2015/08/18 23:17:52  brouard
                    415:   Summary: 0.98q5
                    416: 
1.196     brouard   417:   Revision 1.195  2015/08/18 16:28:39  brouard
                    418:   Summary: Adding a hack for testing purpose
                    419: 
                    420:   After reading the title, ftol and model lines, if the comment line has
                    421:   a q, starting with #q, the answer at the end of the run is quit. It
                    422:   permits to run test files in batch with ctest. The former workaround was
                    423:   $ echo q | imach foo.imach
                    424: 
1.195     brouard   425:   Revision 1.194  2015/08/18 13:32:00  brouard
                    426:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    427: 
1.194     brouard   428:   Revision 1.193  2015/08/04 07:17:42  brouard
                    429:   Summary: 0.98q4
                    430: 
1.193     brouard   431:   Revision 1.192  2015/07/16 16:49:02  brouard
                    432:   Summary: Fixing some outputs
                    433: 
1.192     brouard   434:   Revision 1.191  2015/07/14 10:00:33  brouard
                    435:   Summary: Some fixes
                    436: 
1.191     brouard   437:   Revision 1.190  2015/05/05 08:51:13  brouard
                    438:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    439: 
                    440:   Fix 1+age+.
                    441: 
1.190     brouard   442:   Revision 1.189  2015/04/30 14:45:16  brouard
                    443:   Summary: 0.98q2
                    444: 
1.189     brouard   445:   Revision 1.188  2015/04/30 08:27:53  brouard
                    446:   *** empty log message ***
                    447: 
1.188     brouard   448:   Revision 1.187  2015/04/29 09:11:15  brouard
                    449:   *** empty log message ***
                    450: 
1.187     brouard   451:   Revision 1.186  2015/04/23 12:01:52  brouard
                    452:   Summary: V1*age is working now, version 0.98q1
                    453: 
                    454:   Some codes had been disabled in order to simplify and Vn*age was
                    455:   working in the optimization phase, ie, giving correct MLE parameters,
                    456:   but, as usual, outputs were not correct and program core dumped.
                    457: 
1.186     brouard   458:   Revision 1.185  2015/03/11 13:26:42  brouard
                    459:   Summary: Inclusion of compile and links command line for Intel Compiler
                    460: 
1.185     brouard   461:   Revision 1.184  2015/03/11 11:52:39  brouard
                    462:   Summary: Back from Windows 8. Intel Compiler
                    463: 
1.184     brouard   464:   Revision 1.183  2015/03/10 20:34:32  brouard
                    465:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    466: 
                    467:   We use directest instead of original Powell test; probably no
                    468:   incidence on the results, but better justifications;
                    469:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    470:   wrong results.
                    471: 
1.183     brouard   472:   Revision 1.182  2015/02/12 08:19:57  brouard
                    473:   Summary: Trying to keep directest which seems simpler and more general
                    474:   Author: Nicolas Brouard
                    475: 
1.182     brouard   476:   Revision 1.181  2015/02/11 23:22:24  brouard
                    477:   Summary: Comments on Powell added
                    478: 
                    479:   Author:
                    480: 
1.181     brouard   481:   Revision 1.180  2015/02/11 17:33:45  brouard
                    482:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    483: 
1.180     brouard   484:   Revision 1.179  2015/01/04 09:57:06  brouard
                    485:   Summary: back to OS/X
                    486: 
1.179     brouard   487:   Revision 1.178  2015/01/04 09:35:48  brouard
                    488:   *** empty log message ***
                    489: 
1.178     brouard   490:   Revision 1.177  2015/01/03 18:40:56  brouard
                    491:   Summary: Still testing ilc32 on OSX
                    492: 
1.177     brouard   493:   Revision 1.176  2015/01/03 16:45:04  brouard
                    494:   *** empty log message ***
                    495: 
1.176     brouard   496:   Revision 1.175  2015/01/03 16:33:42  brouard
                    497:   *** empty log message ***
                    498: 
1.175     brouard   499:   Revision 1.174  2015/01/03 16:15:49  brouard
                    500:   Summary: Still in cross-compilation
                    501: 
1.174     brouard   502:   Revision 1.173  2015/01/03 12:06:26  brouard
                    503:   Summary: trying to detect cross-compilation
                    504: 
1.173     brouard   505:   Revision 1.172  2014/12/27 12:07:47  brouard
                    506:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    507: 
1.172     brouard   508:   Revision 1.171  2014/12/23 13:26:59  brouard
                    509:   Summary: Back from Visual C
                    510: 
                    511:   Still problem with utsname.h on Windows
                    512: 
1.171     brouard   513:   Revision 1.170  2014/12/23 11:17:12  brouard
                    514:   Summary: Cleaning some \%% back to %%
                    515: 
                    516:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    517: 
1.170     brouard   518:   Revision 1.169  2014/12/22 23:08:31  brouard
                    519:   Summary: 0.98p
                    520: 
                    521:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    522: 
1.169     brouard   523:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   524:   Summary: update
1.169     brouard   525: 
1.168     brouard   526:   Revision 1.167  2014/12/22 13:50:56  brouard
                    527:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    528: 
                    529:   Testing on Linux 64
                    530: 
1.167     brouard   531:   Revision 1.166  2014/12/22 11:40:47  brouard
                    532:   *** empty log message ***
                    533: 
1.166     brouard   534:   Revision 1.165  2014/12/16 11:20:36  brouard
                    535:   Summary: After compiling on Visual C
                    536: 
                    537:   * imach.c (Module): Merging 1.61 to 1.162
                    538: 
1.165     brouard   539:   Revision 1.164  2014/12/16 10:52:11  brouard
                    540:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    541: 
                    542:   * imach.c (Module): Merging 1.61 to 1.162
                    543: 
1.164     brouard   544:   Revision 1.163  2014/12/16 10:30:11  brouard
                    545:   * imach.c (Module): Merging 1.61 to 1.162
                    546: 
1.163     brouard   547:   Revision 1.162  2014/09/25 11:43:39  brouard
                    548:   Summary: temporary backup 0.99!
                    549: 
1.162     brouard   550:   Revision 1.1  2014/09/16 11:06:58  brouard
                    551:   Summary: With some code (wrong) for nlopt
                    552: 
                    553:   Author:
                    554: 
                    555:   Revision 1.161  2014/09/15 20:41:41  brouard
                    556:   Summary: Problem with macro SQR on Intel compiler
                    557: 
1.161     brouard   558:   Revision 1.160  2014/09/02 09:24:05  brouard
                    559:   *** empty log message ***
                    560: 
1.160     brouard   561:   Revision 1.159  2014/09/01 10:34:10  brouard
                    562:   Summary: WIN32
                    563:   Author: Brouard
                    564: 
1.159     brouard   565:   Revision 1.158  2014/08/27 17:11:51  brouard
                    566:   *** empty log message ***
                    567: 
1.158     brouard   568:   Revision 1.157  2014/08/27 16:26:55  brouard
                    569:   Summary: Preparing windows Visual studio version
                    570:   Author: Brouard
                    571: 
                    572:   In order to compile on Visual studio, time.h is now correct and time_t
                    573:   and tm struct should be used. difftime should be used but sometimes I
                    574:   just make the differences in raw time format (time(&now).
                    575:   Trying to suppress #ifdef LINUX
                    576:   Add xdg-open for __linux in order to open default browser.
                    577: 
1.157     brouard   578:   Revision 1.156  2014/08/25 20:10:10  brouard
                    579:   *** empty log message ***
                    580: 
1.156     brouard   581:   Revision 1.155  2014/08/25 18:32:34  brouard
                    582:   Summary: New compile, minor changes
                    583:   Author: Brouard
                    584: 
1.155     brouard   585:   Revision 1.154  2014/06/20 17:32:08  brouard
                    586:   Summary: Outputs now all graphs of convergence to period prevalence
                    587: 
1.154     brouard   588:   Revision 1.153  2014/06/20 16:45:46  brouard
                    589:   Summary: If 3 live state, convergence to period prevalence on same graph
                    590:   Author: Brouard
                    591: 
1.153     brouard   592:   Revision 1.152  2014/06/18 17:54:09  brouard
                    593:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    594: 
1.152     brouard   595:   Revision 1.151  2014/06/18 16:43:30  brouard
                    596:   *** empty log message ***
                    597: 
1.151     brouard   598:   Revision 1.150  2014/06/18 16:42:35  brouard
                    599:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    600:   Author: brouard
                    601: 
1.150     brouard   602:   Revision 1.149  2014/06/18 15:51:14  brouard
                    603:   Summary: Some fixes in parameter files errors
                    604:   Author: Nicolas Brouard
                    605: 
1.149     brouard   606:   Revision 1.148  2014/06/17 17:38:48  brouard
                    607:   Summary: Nothing new
                    608:   Author: Brouard
                    609: 
                    610:   Just a new packaging for OS/X version 0.98nS
                    611: 
1.148     brouard   612:   Revision 1.147  2014/06/16 10:33:11  brouard
                    613:   *** empty log message ***
                    614: 
1.147     brouard   615:   Revision 1.146  2014/06/16 10:20:28  brouard
                    616:   Summary: Merge
                    617:   Author: Brouard
                    618: 
                    619:   Merge, before building revised version.
                    620: 
1.146     brouard   621:   Revision 1.145  2014/06/10 21:23:15  brouard
                    622:   Summary: Debugging with valgrind
                    623:   Author: Nicolas Brouard
                    624: 
                    625:   Lot of changes in order to output the results with some covariates
                    626:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    627:   improve the code.
                    628:   No more memory valgrind error but a lot has to be done in order to
                    629:   continue the work of splitting the code into subroutines.
                    630:   Also, decodemodel has been improved. Tricode is still not
                    631:   optimal. nbcode should be improved. Documentation has been added in
                    632:   the source code.
                    633: 
1.144     brouard   634:   Revision 1.143  2014/01/26 09:45:38  brouard
                    635:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    636: 
                    637:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    638:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    639: 
1.143     brouard   640:   Revision 1.142  2014/01/26 03:57:36  brouard
                    641:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    642: 
                    643:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    644: 
1.142     brouard   645:   Revision 1.141  2014/01/26 02:42:01  brouard
                    646:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    647: 
1.141     brouard   648:   Revision 1.140  2011/09/02 10:37:54  brouard
                    649:   Summary: times.h is ok with mingw32 now.
                    650: 
1.140     brouard   651:   Revision 1.139  2010/06/14 07:50:17  brouard
                    652:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    653:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    654: 
1.139     brouard   655:   Revision 1.138  2010/04/30 18:19:40  brouard
                    656:   *** empty log message ***
                    657: 
1.138     brouard   658:   Revision 1.137  2010/04/29 18:11:38  brouard
                    659:   (Module): Checking covariates for more complex models
                    660:   than V1+V2. A lot of change to be done. Unstable.
                    661: 
1.137     brouard   662:   Revision 1.136  2010/04/26 20:30:53  brouard
                    663:   (Module): merging some libgsl code. Fixing computation
                    664:   of likelione (using inter/intrapolation if mle = 0) in order to
                    665:   get same likelihood as if mle=1.
                    666:   Some cleaning of code and comments added.
                    667: 
1.136     brouard   668:   Revision 1.135  2009/10/29 15:33:14  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.135     brouard   671:   Revision 1.134  2009/10/29 13:18:53  brouard
                    672:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    673: 
1.134     brouard   674:   Revision 1.133  2009/07/06 10:21:25  brouard
                    675:   just nforces
                    676: 
1.133     brouard   677:   Revision 1.132  2009/07/06 08:22:05  brouard
                    678:   Many tings
                    679: 
1.132     brouard   680:   Revision 1.131  2009/06/20 16:22:47  brouard
                    681:   Some dimensions resccaled
                    682: 
1.131     brouard   683:   Revision 1.130  2009/05/26 06:44:34  brouard
                    684:   (Module): Max Covariate is now set to 20 instead of 8. A
                    685:   lot of cleaning with variables initialized to 0. Trying to make
                    686:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    687: 
1.130     brouard   688:   Revision 1.129  2007/08/31 13:49:27  lievre
                    689:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    690: 
1.129     lievre    691:   Revision 1.128  2006/06/30 13:02:05  brouard
                    692:   (Module): Clarifications on computing e.j
                    693: 
1.128     brouard   694:   Revision 1.127  2006/04/28 18:11:50  brouard
                    695:   (Module): Yes the sum of survivors was wrong since
                    696:   imach-114 because nhstepm was no more computed in the age
                    697:   loop. Now we define nhstepma in the age loop.
                    698:   (Module): In order to speed up (in case of numerous covariates) we
                    699:   compute health expectancies (without variances) in a first step
                    700:   and then all the health expectancies with variances or standard
                    701:   deviation (needs data from the Hessian matrices) which slows the
                    702:   computation.
                    703:   In the future we should be able to stop the program is only health
                    704:   expectancies and graph are needed without standard deviations.
                    705: 
1.127     brouard   706:   Revision 1.126  2006/04/28 17:23:28  brouard
                    707:   (Module): Yes the sum of survivors was wrong since
                    708:   imach-114 because nhstepm was no more computed in the age
                    709:   loop. Now we define nhstepma in the age loop.
                    710:   Version 0.98h
                    711: 
1.126     brouard   712:   Revision 1.125  2006/04/04 15:20:31  lievre
                    713:   Errors in calculation of health expectancies. Age was not initialized.
                    714:   Forecasting file added.
                    715: 
                    716:   Revision 1.124  2006/03/22 17:13:53  lievre
                    717:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    718:   The log-likelihood is printed in the log file
                    719: 
                    720:   Revision 1.123  2006/03/20 10:52:43  brouard
                    721:   * imach.c (Module): <title> changed, corresponds to .htm file
                    722:   name. <head> headers where missing.
                    723: 
                    724:   * imach.c (Module): Weights can have a decimal point as for
                    725:   English (a comma might work with a correct LC_NUMERIC environment,
                    726:   otherwise the weight is truncated).
                    727:   Modification of warning when the covariates values are not 0 or
                    728:   1.
                    729:   Version 0.98g
                    730: 
                    731:   Revision 1.122  2006/03/20 09:45:41  brouard
                    732:   (Module): Weights can have a decimal point as for
                    733:   English (a comma might work with a correct LC_NUMERIC environment,
                    734:   otherwise the weight is truncated).
                    735:   Modification of warning when the covariates values are not 0 or
                    736:   1.
                    737:   Version 0.98g
                    738: 
                    739:   Revision 1.121  2006/03/16 17:45:01  lievre
                    740:   * imach.c (Module): Comments concerning covariates added
                    741: 
                    742:   * imach.c (Module): refinements in the computation of lli if
                    743:   status=-2 in order to have more reliable computation if stepm is
                    744:   not 1 month. Version 0.98f
                    745: 
                    746:   Revision 1.120  2006/03/16 15:10:38  lievre
                    747:   (Module): refinements in the computation of lli if
                    748:   status=-2 in order to have more reliable computation if stepm is
                    749:   not 1 month. Version 0.98f
                    750: 
                    751:   Revision 1.119  2006/03/15 17:42:26  brouard
                    752:   (Module): Bug if status = -2, the loglikelihood was
                    753:   computed as likelihood omitting the logarithm. Version O.98e
                    754: 
                    755:   Revision 1.118  2006/03/14 18:20:07  brouard
                    756:   (Module): varevsij Comments added explaining the second
                    757:   table of variances if popbased=1 .
                    758:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    759:   (Module): Function pstamp added
                    760:   (Module): Version 0.98d
                    761: 
                    762:   Revision 1.117  2006/03/14 17:16:22  brouard
                    763:   (Module): varevsij Comments added explaining the second
                    764:   table of variances if popbased=1 .
                    765:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    766:   (Module): Function pstamp added
                    767:   (Module): Version 0.98d
                    768: 
                    769:   Revision 1.116  2006/03/06 10:29:27  brouard
                    770:   (Module): Variance-covariance wrong links and
                    771:   varian-covariance of ej. is needed (Saito).
                    772: 
                    773:   Revision 1.115  2006/02/27 12:17:45  brouard
                    774:   (Module): One freematrix added in mlikeli! 0.98c
                    775: 
                    776:   Revision 1.114  2006/02/26 12:57:58  brouard
                    777:   (Module): Some improvements in processing parameter
                    778:   filename with strsep.
                    779: 
                    780:   Revision 1.113  2006/02/24 14:20:24  brouard
                    781:   (Module): Memory leaks checks with valgrind and:
                    782:   datafile was not closed, some imatrix were not freed and on matrix
                    783:   allocation too.
                    784: 
                    785:   Revision 1.112  2006/01/30 09:55:26  brouard
                    786:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    787: 
                    788:   Revision 1.111  2006/01/25 20:38:18  brouard
                    789:   (Module): Lots of cleaning and bugs added (Gompertz)
                    790:   (Module): Comments can be added in data file. Missing date values
                    791:   can be a simple dot '.'.
                    792: 
                    793:   Revision 1.110  2006/01/25 00:51:50  brouard
                    794:   (Module): Lots of cleaning and bugs added (Gompertz)
                    795: 
                    796:   Revision 1.109  2006/01/24 19:37:15  brouard
                    797:   (Module): Comments (lines starting with a #) are allowed in data.
                    798: 
                    799:   Revision 1.108  2006/01/19 18:05:42  lievre
                    800:   Gnuplot problem appeared...
                    801:   To be fixed
                    802: 
                    803:   Revision 1.107  2006/01/19 16:20:37  brouard
                    804:   Test existence of gnuplot in imach path
                    805: 
                    806:   Revision 1.106  2006/01/19 13:24:36  brouard
                    807:   Some cleaning and links added in html output
                    808: 
                    809:   Revision 1.105  2006/01/05 20:23:19  lievre
                    810:   *** empty log message ***
                    811: 
                    812:   Revision 1.104  2005/09/30 16:11:43  lievre
                    813:   (Module): sump fixed, loop imx fixed, and simplifications.
                    814:   (Module): If the status is missing at the last wave but we know
                    815:   that the person is alive, then we can code his/her status as -2
                    816:   (instead of missing=-1 in earlier versions) and his/her
                    817:   contributions to the likelihood is 1 - Prob of dying from last
                    818:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    819:   the healthy state at last known wave). Version is 0.98
                    820: 
                    821:   Revision 1.103  2005/09/30 15:54:49  lievre
                    822:   (Module): sump fixed, loop imx fixed, and simplifications.
                    823: 
                    824:   Revision 1.102  2004/09/15 17:31:30  brouard
                    825:   Add the possibility to read data file including tab characters.
                    826: 
                    827:   Revision 1.101  2004/09/15 10:38:38  brouard
                    828:   Fix on curr_time
                    829: 
                    830:   Revision 1.100  2004/07/12 18:29:06  brouard
                    831:   Add version for Mac OS X. Just define UNIX in Makefile
                    832: 
                    833:   Revision 1.99  2004/06/05 08:57:40  brouard
                    834:   *** empty log message ***
                    835: 
                    836:   Revision 1.98  2004/05/16 15:05:56  brouard
                    837:   New version 0.97 . First attempt to estimate force of mortality
                    838:   directly from the data i.e. without the need of knowing the health
                    839:   state at each age, but using a Gompertz model: log u =a + b*age .
                    840:   This is the basic analysis of mortality and should be done before any
                    841:   other analysis, in order to test if the mortality estimated from the
                    842:   cross-longitudinal survey is different from the mortality estimated
                    843:   from other sources like vital statistic data.
                    844: 
                    845:   The same imach parameter file can be used but the option for mle should be -3.
                    846: 
1.133     brouard   847:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   848:   former routines in order to include the new code within the former code.
                    849: 
                    850:   The output is very simple: only an estimate of the intercept and of
                    851:   the slope with 95% confident intervals.
                    852: 
                    853:   Current limitations:
                    854:   A) Even if you enter covariates, i.e. with the
                    855:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    856:   B) There is no computation of Life Expectancy nor Life Table.
                    857: 
                    858:   Revision 1.97  2004/02/20 13:25:42  lievre
                    859:   Version 0.96d. Population forecasting command line is (temporarily)
                    860:   suppressed.
                    861: 
                    862:   Revision 1.96  2003/07/15 15:38:55  brouard
                    863:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    864:   rewritten within the same printf. Workaround: many printfs.
                    865: 
                    866:   Revision 1.95  2003/07/08 07:54:34  brouard
                    867:   * imach.c (Repository):
                    868:   (Repository): Using imachwizard code to output a more meaningful covariance
                    869:   matrix (cov(a12,c31) instead of numbers.
                    870: 
                    871:   Revision 1.94  2003/06/27 13:00:02  brouard
                    872:   Just cleaning
                    873: 
                    874:   Revision 1.93  2003/06/25 16:33:55  brouard
                    875:   (Module): On windows (cygwin) function asctime_r doesn't
                    876:   exist so I changed back to asctime which exists.
                    877:   (Module): Version 0.96b
                    878: 
                    879:   Revision 1.92  2003/06/25 16:30:45  brouard
                    880:   (Module): On windows (cygwin) function asctime_r doesn't
                    881:   exist so I changed back to asctime which exists.
                    882: 
                    883:   Revision 1.91  2003/06/25 15:30:29  brouard
                    884:   * imach.c (Repository): Duplicated warning errors corrected.
                    885:   (Repository): Elapsed time after each iteration is now output. It
                    886:   helps to forecast when convergence will be reached. Elapsed time
                    887:   is stamped in powell.  We created a new html file for the graphs
                    888:   concerning matrix of covariance. It has extension -cov.htm.
                    889: 
                    890:   Revision 1.90  2003/06/24 12:34:15  brouard
                    891:   (Module): Some bugs corrected for windows. Also, when
                    892:   mle=-1 a template is output in file "or"mypar.txt with the design
                    893:   of the covariance matrix to be input.
                    894: 
                    895:   Revision 1.89  2003/06/24 12:30:52  brouard
                    896:   (Module): Some bugs corrected for windows. Also, when
                    897:   mle=-1 a template is output in file "or"mypar.txt with the design
                    898:   of the covariance matrix to be input.
                    899: 
                    900:   Revision 1.88  2003/06/23 17:54:56  brouard
                    901:   * 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.
                    902: 
                    903:   Revision 1.87  2003/06/18 12:26:01  brouard
                    904:   Version 0.96
                    905: 
                    906:   Revision 1.86  2003/06/17 20:04:08  brouard
                    907:   (Module): Change position of html and gnuplot routines and added
                    908:   routine fileappend.
                    909: 
                    910:   Revision 1.85  2003/06/17 13:12:43  brouard
                    911:   * imach.c (Repository): Check when date of death was earlier that
                    912:   current date of interview. It may happen when the death was just
                    913:   prior to the death. In this case, dh was negative and likelihood
                    914:   was wrong (infinity). We still send an "Error" but patch by
                    915:   assuming that the date of death was just one stepm after the
                    916:   interview.
                    917:   (Repository): Because some people have very long ID (first column)
                    918:   we changed int to long in num[] and we added a new lvector for
                    919:   memory allocation. But we also truncated to 8 characters (left
                    920:   truncation)
                    921:   (Repository): No more line truncation errors.
                    922: 
                    923:   Revision 1.84  2003/06/13 21:44:43  brouard
                    924:   * imach.c (Repository): Replace "freqsummary" at a correct
                    925:   place. It differs from routine "prevalence" which may be called
                    926:   many times. Probs is memory consuming and must be used with
                    927:   parcimony.
                    928:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    929: 
                    930:   Revision 1.83  2003/06/10 13:39:11  lievre
                    931:   *** empty log message ***
                    932: 
                    933:   Revision 1.82  2003/06/05 15:57:20  brouard
                    934:   Add log in  imach.c and  fullversion number is now printed.
                    935: 
                    936: */
                    937: /*
                    938:    Interpolated Markov Chain
                    939: 
                    940:   Short summary of the programme:
                    941:   
1.227     brouard   942:   This program computes Healthy Life Expectancies or State-specific
                    943:   (if states aren't health statuses) Expectancies from
                    944:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    945: 
                    946:   -1- a first survey ("cross") where individuals from different ages
                    947:   are interviewed on their health status or degree of disability (in
                    948:   the case of a health survey which is our main interest)
                    949: 
                    950:   -2- at least a second wave of interviews ("longitudinal") which
                    951:   measure each change (if any) in individual health status.  Health
                    952:   expectancies are computed from the time spent in each health state
                    953:   according to a model. More health states you consider, more time is
                    954:   necessary to reach the Maximum Likelihood of the parameters involved
                    955:   in the model.  The simplest model is the multinomial logistic model
                    956:   where pij is the probability to be observed in state j at the second
                    957:   wave conditional to be observed in state i at the first
                    958:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    959:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    960:   have a more complex model than "constant and age", you should modify
                    961:   the program where the markup *Covariates have to be included here
                    962:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   963:   convergence.
                    964: 
                    965:   The advantage of this computer programme, compared to a simple
                    966:   multinomial logistic model, is clear when the delay between waves is not
                    967:   identical for each individual. Also, if a individual missed an
                    968:   intermediate interview, the information is lost, but taken into
                    969:   account using an interpolation or extrapolation.  
                    970: 
                    971:   hPijx is the probability to be observed in state i at age x+h
                    972:   conditional to the observed state i at age x. The delay 'h' can be
                    973:   split into an exact number (nh*stepm) of unobserved intermediate
                    974:   states. This elementary transition (by month, quarter,
                    975:   semester or year) is modelled as a multinomial logistic.  The hPx
                    976:   matrix is simply the matrix product of nh*stepm elementary matrices
                    977:   and the contribution of each individual to the likelihood is simply
                    978:   hPijx.
                    979: 
                    980:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   981:   of the life expectancies. It also computes the period (stable) prevalence.
                    982: 
                    983: Back prevalence and projections:
1.227     brouard   984: 
                    985:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    986:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    987:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    988:    mobilavproj)
                    989: 
                    990:     Computes the back prevalence limit for any combination of
                    991:     covariate values k at any age between ageminpar and agemaxpar and
                    992:     returns it in **bprlim. In the loops,
                    993: 
                    994:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    995:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    996: 
                    997:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   998:    Computes for any combination of covariates k and any age between bage and fage 
                    999:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1000:                        oldm=oldms;savm=savms;
1.227     brouard  1001: 
1.267     brouard  1002:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1003:      Computes the transition matrix starting at age 'age' over
                   1004:      'nhstepm*hstepm*stepm' months (i.e. until
                   1005:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1006:      nhstepm*hstepm matrices. 
                   1007: 
                   1008:      Returns p3mat[i][j][h] after calling
                   1009:      p3mat[i][j][h]=matprod2(newm,
                   1010:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1011:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1012:      oldm);
1.226     brouard  1013: 
                   1014: Important routines
                   1015: 
                   1016: - func (or funcone), computes logit (pij) distinguishing
                   1017:   o fixed variables (single or product dummies or quantitative);
                   1018:   o varying variables by:
                   1019:    (1) wave (single, product dummies, quantitative), 
                   1020:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1021:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1022:        % varying dummy (not done) or quantitative (not done);
                   1023: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1024:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1025: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                   1026:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                   1027:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1028: 
1.226     brouard  1029: 
                   1030:   
1.133     brouard  1031:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1032:            Institut national d'études démographiques, Paris.
1.126     brouard  1033:   This software have been partly granted by Euro-REVES, a concerted action
                   1034:   from the European Union.
                   1035:   It is copyrighted identically to a GNU software product, ie programme and
                   1036:   software can be distributed freely for non commercial use. Latest version
                   1037:   can be accessed at http://euroreves.ined.fr/imach .
                   1038: 
                   1039:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1040:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1041:   
                   1042:   **********************************************************************/
                   1043: /*
                   1044:   main
                   1045:   read parameterfile
                   1046:   read datafile
                   1047:   concatwav
                   1048:   freqsummary
                   1049:   if (mle >= 1)
                   1050:     mlikeli
                   1051:   print results files
                   1052:   if mle==1 
                   1053:      computes hessian
                   1054:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1055:       begin-prev-date,...
                   1056:   open gnuplot file
                   1057:   open html file
1.145     brouard  1058:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1059:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1060:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1061:     freexexit2 possible for memory heap.
                   1062: 
                   1063:   h Pij x                         | pij_nom  ficrestpij
                   1064:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1065:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1066:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1067: 
                   1068:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1069:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1070:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1071:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1072:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1073: 
1.126     brouard  1074:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1075:   health expectancies
                   1076:   Variance-covariance of DFLE
                   1077:   prevalence()
                   1078:    movingaverage()
                   1079:   varevsij() 
                   1080:   if popbased==1 varevsij(,popbased)
                   1081:   total life expectancies
                   1082:   Variance of period (stable) prevalence
                   1083:  end
                   1084: */
                   1085: 
1.187     brouard  1086: /* #define DEBUG */
                   1087: /* #define DEBUGBRENT */
1.203     brouard  1088: /* #define DEBUGLINMIN */
                   1089: /* #define DEBUGHESS */
                   1090: #define DEBUGHESSIJ
1.224     brouard  1091: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1092: #define POWELL /* Instead of NLOPT */
1.224     brouard  1093: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1094: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1095: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1096: 
                   1097: #include <math.h>
                   1098: #include <stdio.h>
                   1099: #include <stdlib.h>
                   1100: #include <string.h>
1.226     brouard  1101: #include <ctype.h>
1.159     brouard  1102: 
                   1103: #ifdef _WIN32
                   1104: #include <io.h>
1.172     brouard  1105: #include <windows.h>
                   1106: #include <tchar.h>
1.159     brouard  1107: #else
1.126     brouard  1108: #include <unistd.h>
1.159     brouard  1109: #endif
1.126     brouard  1110: 
                   1111: #include <limits.h>
                   1112: #include <sys/types.h>
1.171     brouard  1113: 
                   1114: #if defined(__GNUC__)
                   1115: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1116: #endif
                   1117: 
1.126     brouard  1118: #include <sys/stat.h>
                   1119: #include <errno.h>
1.159     brouard  1120: /* extern int errno; */
1.126     brouard  1121: 
1.157     brouard  1122: /* #ifdef LINUX */
                   1123: /* #include <time.h> */
                   1124: /* #include "timeval.h" */
                   1125: /* #else */
                   1126: /* #include <sys/time.h> */
                   1127: /* #endif */
                   1128: 
1.126     brouard  1129: #include <time.h>
                   1130: 
1.136     brouard  1131: #ifdef GSL
                   1132: #include <gsl/gsl_errno.h>
                   1133: #include <gsl/gsl_multimin.h>
                   1134: #endif
                   1135: 
1.167     brouard  1136: 
1.162     brouard  1137: #ifdef NLOPT
                   1138: #include <nlopt.h>
                   1139: typedef struct {
                   1140:   double (* function)(double [] );
                   1141: } myfunc_data ;
                   1142: #endif
                   1143: 
1.126     brouard  1144: /* #include <libintl.h> */
                   1145: /* #define _(String) gettext (String) */
                   1146: 
1.251     brouard  1147: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1148: 
                   1149: #define GNUPLOTPROGRAM "gnuplot"
                   1150: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1151: #define FILENAMELENGTH 132
                   1152: 
                   1153: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1154: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1155: 
1.144     brouard  1156: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1157: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1158: 
                   1159: #define NINTERVMAX 8
1.144     brouard  1160: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1161: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1162: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1163: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1164: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1165: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1166: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1167: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1168: /* #define AGESUP 130 */
1.288     brouard  1169: /* #define AGESUP 150 */
                   1170: #define AGESUP 200
1.268     brouard  1171: #define AGEINF 0
1.218     brouard  1172: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1173: #define AGEBASE 40
1.194     brouard  1174: #define AGEOVERFLOW 1.e20
1.164     brouard  1175: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1176: #ifdef _WIN32
                   1177: #define DIRSEPARATOR '\\'
                   1178: #define CHARSEPARATOR "\\"
                   1179: #define ODIRSEPARATOR '/'
                   1180: #else
1.126     brouard  1181: #define DIRSEPARATOR '/'
                   1182: #define CHARSEPARATOR "/"
                   1183: #define ODIRSEPARATOR '\\'
                   1184: #endif
                   1185: 
1.317   ! brouard  1186: /* $Id: imach.c,v 1.316 2022/05/11 15:11:31 brouard Exp $ */
1.126     brouard  1187: /* $State: Exp $ */
1.196     brouard  1188: #include "version.h"
                   1189: char version[]=__IMACH_VERSION__;
1.316     brouard  1190: char copyright[]="May 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.317   ! brouard  1191: char fullversion[]="$Revision: 1.316 $ $Date: 2022/05/11 15:11:31 $"; 
1.126     brouard  1192: char strstart[80];
                   1193: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1194: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1195: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1196: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1197: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1198: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1199: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1200: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1201: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1202: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1203: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1204: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1205: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1206: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1207: int nsd=0; /**< Total number of single dummy variables (output) */
                   1208: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1209: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1210: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1211: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1212: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1213: int cptcov=0; /* Working variable */
1.290     brouard  1214: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1215: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1216: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1217: int nlstate=2; /* Number of live states */
                   1218: int ndeath=1; /* Number of dead states */
1.130     brouard  1219: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1220: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1221: int popbased=0;
                   1222: 
                   1223: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1224: int maxwav=0; /* Maxim number of waves */
                   1225: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1226: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1227: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1228:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1229: int mle=1, weightopt=0;
1.126     brouard  1230: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1231: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1232: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1233:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1234: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1235: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1236: 
1.130     brouard  1237: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1238: double **matprod2(); /* test */
1.126     brouard  1239: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1240: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1241: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1242: 
1.136     brouard  1243: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1244: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1245: FILE *ficlog, *ficrespow;
1.130     brouard  1246: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1247: double fretone; /* Only one call to likelihood */
1.130     brouard  1248: long ipmx=0; /* Number of contributions */
1.126     brouard  1249: double sw; /* Sum of weights */
                   1250: char filerespow[FILENAMELENGTH];
                   1251: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1252: FILE *ficresilk;
                   1253: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1254: FILE *ficresprobmorprev;
                   1255: FILE *fichtm, *fichtmcov; /* Html File */
                   1256: FILE *ficreseij;
                   1257: char filerese[FILENAMELENGTH];
                   1258: FILE *ficresstdeij;
                   1259: char fileresstde[FILENAMELENGTH];
                   1260: FILE *ficrescveij;
                   1261: char filerescve[FILENAMELENGTH];
                   1262: FILE  *ficresvij;
                   1263: char fileresv[FILENAMELENGTH];
1.269     brouard  1264: 
1.126     brouard  1265: char title[MAXLINE];
1.234     brouard  1266: char model[MAXLINE]; /**< The model line */
1.217     brouard  1267: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1268: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1269: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1270: char command[FILENAMELENGTH];
                   1271: int  outcmd=0;
                   1272: 
1.217     brouard  1273: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1274: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1275: char filelog[FILENAMELENGTH]; /* Log file */
                   1276: char filerest[FILENAMELENGTH];
                   1277: char fileregp[FILENAMELENGTH];
                   1278: char popfile[FILENAMELENGTH];
                   1279: 
                   1280: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1281: 
1.157     brouard  1282: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1283: /* struct timezone tzp; */
                   1284: /* extern int gettimeofday(); */
                   1285: struct tm tml, *gmtime(), *localtime();
                   1286: 
                   1287: extern time_t time();
                   1288: 
                   1289: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1290: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1291: struct tm tm;
                   1292: 
1.126     brouard  1293: char strcurr[80], strfor[80];
                   1294: 
                   1295: char *endptr;
                   1296: long lval;
                   1297: double dval;
                   1298: 
                   1299: #define NR_END 1
                   1300: #define FREE_ARG char*
                   1301: #define FTOL 1.0e-10
                   1302: 
                   1303: #define NRANSI 
1.240     brouard  1304: #define ITMAX 200
                   1305: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1306: 
                   1307: #define TOL 2.0e-4 
                   1308: 
                   1309: #define CGOLD 0.3819660 
                   1310: #define ZEPS 1.0e-10 
                   1311: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1312: 
                   1313: #define GOLD 1.618034 
                   1314: #define GLIMIT 100.0 
                   1315: #define TINY 1.0e-20 
                   1316: 
                   1317: static double maxarg1,maxarg2;
                   1318: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1319: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1320:   
                   1321: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1322: #define rint(a) floor(a+0.5)
1.166     brouard  1323: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1324: #define mytinydouble 1.0e-16
1.166     brouard  1325: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1326: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1327: /* static double dsqrarg; */
                   1328: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1329: static double sqrarg;
                   1330: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1331: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1332: int agegomp= AGEGOMP;
                   1333: 
                   1334: int imx; 
                   1335: int stepm=1;
                   1336: /* Stepm, step in month: minimum step interpolation*/
                   1337: 
                   1338: int estepm;
                   1339: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1340: 
                   1341: int m,nb;
                   1342: long *num;
1.197     brouard  1343: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1344: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1345:                   covariate for which somebody answered excluding 
                   1346:                   undefined. Usually 2: 0 and 1. */
                   1347: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1348:                             covariate for which somebody answered including 
                   1349:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1350: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1351: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1352: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1353: double *ageexmed,*agecens;
                   1354: double dateintmean=0;
1.296     brouard  1355:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1356:   double anprojf, mprojf, jprojf;
1.126     brouard  1357: 
1.296     brouard  1358:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1359:   double anbackf, mbackf, jbackf;
                   1360:   double jintmean,mintmean,aintmean;  
1.126     brouard  1361: double *weight;
                   1362: int **s; /* Status */
1.141     brouard  1363: double *agedc;
1.145     brouard  1364: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1365:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1366:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1367: double **coqvar; /* Fixed quantitative covariate nqv */
                   1368: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1369: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1370: double  idx; 
                   1371: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1372: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1373: /*k          1  2   3   4     5    6    7     8    9 */
                   1374: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1375: /* Tndvar[k]    1   2   3               4          5 */
                   1376: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1377: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1378: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1379: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1380: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1381: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1382: /* Tprod[i]=k           4               7            */
                   1383: /* Tage[i]=k                  5               8      */
                   1384: /* */
                   1385: /* Type                    */
                   1386: /* V         1  2  3  4  5 */
                   1387: /*           F  F  V  V  V */
                   1388: /*           D  Q  D  D  Q */
                   1389: /*                         */
                   1390: int *TvarsD;
                   1391: int *TvarsDind;
                   1392: int *TvarsQ;
                   1393: int *TvarsQind;
                   1394: 
1.235     brouard  1395: #define MAXRESULTLINES 10
                   1396: int nresult=0;
1.258     brouard  1397: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1398: int TKresult[MAXRESULTLINES];
1.237     brouard  1399: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1400: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1401: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1402: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1403: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1404: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1405: 
1.234     brouard  1406: /* 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  1407: 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 */
                   1408: 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 */
                   1409: 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 */
                   1410: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1411: 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 */
                   1412: 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  1413: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1414: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1415: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1416: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1417: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1418: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1419: 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 */
                   1420: 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 */
                   1421: 
1.230     brouard  1422: int *Tvarsel; /**< Selected covariates for output */
                   1423: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1424: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1425: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1426: 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  1427: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1428: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1429: int *Tage;
1.227     brouard  1430: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1431: 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  1432: 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*/ 
                   1433: 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  1434: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1435: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1436: int **Tvard;
                   1437: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1438: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1439: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1440:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1441:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1442: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1443: double *lsurv, *lpop, *tpop;
                   1444: 
1.231     brouard  1445: #define FD 1; /* Fixed dummy covariate */
                   1446: #define FQ 2; /* Fixed quantitative covariate */
                   1447: #define FP 3; /* Fixed product covariate */
                   1448: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1449: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1450: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1451: #define VD 10; /* Varying dummy covariate */
                   1452: #define VQ 11; /* Varying quantitative covariate */
                   1453: #define VP 12; /* Varying product covariate */
                   1454: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1455: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1456: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1457: #define APFD 16; /* Age product * fixed dummy covariate */
                   1458: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1459: #define APVD 18; /* Age product * varying dummy covariate */
                   1460: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1461: 
                   1462: #define FTYPE 1; /* Fixed covariate */
                   1463: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1464: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1465: 
                   1466: struct kmodel{
                   1467:        int maintype; /* main type */
                   1468:        int subtype; /* subtype */
                   1469: };
                   1470: struct kmodel modell[NCOVMAX];
                   1471: 
1.143     brouard  1472: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1473: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1474: 
                   1475: /**************** split *************************/
                   1476: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1477: {
                   1478:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1479:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1480:   */ 
                   1481:   char *ss;                            /* pointer */
1.186     brouard  1482:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1483: 
                   1484:   l1 = strlen(path );                  /* length of path */
                   1485:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1486:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1487:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1488:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1489:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1490:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1491:     /* get current working directory */
                   1492:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1493: #ifdef WIN32
                   1494:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1495: #else
                   1496:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1497: #endif
1.126     brouard  1498:       return( GLOCK_ERROR_GETCWD );
                   1499:     }
                   1500:     /* got dirc from getcwd*/
                   1501:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1502:   } else {                             /* strip directory from path */
1.126     brouard  1503:     ss++;                              /* after this, the filename */
                   1504:     l2 = strlen( ss );                 /* length of filename */
                   1505:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1506:     strcpy( name, ss );                /* save file name */
                   1507:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1508:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1509:     printf(" DIRC2 = %s \n",dirc);
                   1510:   }
                   1511:   /* We add a separator at the end of dirc if not exists */
                   1512:   l1 = strlen( dirc );                 /* length of directory */
                   1513:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1514:     dirc[l1] =  DIRSEPARATOR;
                   1515:     dirc[l1+1] = 0; 
                   1516:     printf(" DIRC3 = %s \n",dirc);
                   1517:   }
                   1518:   ss = strrchr( name, '.' );           /* find last / */
                   1519:   if (ss >0){
                   1520:     ss++;
                   1521:     strcpy(ext,ss);                    /* save extension */
                   1522:     l1= strlen( name);
                   1523:     l2= strlen(ss)+1;
                   1524:     strncpy( finame, name, l1-l2);
                   1525:     finame[l1-l2]= 0;
                   1526:   }
                   1527: 
                   1528:   return( 0 );                         /* we're done */
                   1529: }
                   1530: 
                   1531: 
                   1532: /******************************************/
                   1533: 
                   1534: void replace_back_to_slash(char *s, char*t)
                   1535: {
                   1536:   int i;
                   1537:   int lg=0;
                   1538:   i=0;
                   1539:   lg=strlen(t);
                   1540:   for(i=0; i<= lg; i++) {
                   1541:     (s[i] = t[i]);
                   1542:     if (t[i]== '\\') s[i]='/';
                   1543:   }
                   1544: }
                   1545: 
1.132     brouard  1546: char *trimbb(char *out, char *in)
1.137     brouard  1547: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1548:   char *s;
                   1549:   s=out;
                   1550:   while (*in != '\0'){
1.137     brouard  1551:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1552:       in++;
                   1553:     }
                   1554:     *out++ = *in++;
                   1555:   }
                   1556:   *out='\0';
                   1557:   return s;
                   1558: }
                   1559: 
1.187     brouard  1560: /* char *substrchaine(char *out, char *in, char *chain) */
                   1561: /* { */
                   1562: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1563: /*   char *s, *t; */
                   1564: /*   t=in;s=out; */
                   1565: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1566: /*     *out++ = *in++; */
                   1567: /*   } */
                   1568: 
                   1569: /*   /\* *in matches *chain *\/ */
                   1570: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1571: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1572: /*   } */
                   1573: /*   in--; chain--; */
                   1574: /*   while ( (*in != '\0')){ */
                   1575: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1576: /*     *out++ = *in++; */
                   1577: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1578: /*   } */
                   1579: /*   *out='\0'; */
                   1580: /*   out=s; */
                   1581: /*   return out; */
                   1582: /* } */
                   1583: char *substrchaine(char *out, char *in, char *chain)
                   1584: {
                   1585:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1586:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1587: 
                   1588:   char *strloc;
                   1589: 
                   1590:   strcpy (out, in); 
                   1591:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1592:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1593:   if(strloc != NULL){ 
                   1594:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1595:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1596:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1597:   }
                   1598:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1599:   return out;
                   1600: }
                   1601: 
                   1602: 
1.145     brouard  1603: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1604: {
1.187     brouard  1605:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1606:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1607:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1608:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1609:   */
1.160     brouard  1610:   char *s, *t;
1.145     brouard  1611:   t=in;s=in;
                   1612:   while ((*in != occ) && (*in != '\0')){
                   1613:     *alocc++ = *in++;
                   1614:   }
                   1615:   if( *in == occ){
                   1616:     *(alocc)='\0';
                   1617:     s=++in;
                   1618:   }
                   1619:  
                   1620:   if (s == t) {/* occ not found */
                   1621:     *(alocc-(in-s))='\0';
                   1622:     in=s;
                   1623:   }
                   1624:   while ( *in != '\0'){
                   1625:     *blocc++ = *in++;
                   1626:   }
                   1627: 
                   1628:   *blocc='\0';
                   1629:   return t;
                   1630: }
1.137     brouard  1631: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1632: {
1.187     brouard  1633:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1634:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1635:      gives blocc="abcdef2ghi" and alocc="j".
                   1636:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1637:   */
                   1638:   char *s, *t;
                   1639:   t=in;s=in;
                   1640:   while (*in != '\0'){
                   1641:     while( *in == occ){
                   1642:       *blocc++ = *in++;
                   1643:       s=in;
                   1644:     }
                   1645:     *blocc++ = *in++;
                   1646:   }
                   1647:   if (s == t) /* occ not found */
                   1648:     *(blocc-(in-s))='\0';
                   1649:   else
                   1650:     *(blocc-(in-s)-1)='\0';
                   1651:   in=s;
                   1652:   while ( *in != '\0'){
                   1653:     *alocc++ = *in++;
                   1654:   }
                   1655: 
                   1656:   *alocc='\0';
                   1657:   return s;
                   1658: }
                   1659: 
1.126     brouard  1660: int nbocc(char *s, char occ)
                   1661: {
                   1662:   int i,j=0;
                   1663:   int lg=20;
                   1664:   i=0;
                   1665:   lg=strlen(s);
                   1666:   for(i=0; i<= lg; i++) {
1.234     brouard  1667:     if  (s[i] == occ ) j++;
1.126     brouard  1668:   }
                   1669:   return j;
                   1670: }
                   1671: 
1.137     brouard  1672: /* void cutv(char *u,char *v, char*t, char occ) */
                   1673: /* { */
                   1674: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1675: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1676: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1677: /*   int i,lg,j,p=0; */
                   1678: /*   i=0; */
                   1679: /*   lg=strlen(t); */
                   1680: /*   for(j=0; j<=lg-1; j++) { */
                   1681: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1682: /*   } */
1.126     brouard  1683: 
1.137     brouard  1684: /*   for(j=0; j<p; j++) { */
                   1685: /*     (u[j] = t[j]); */
                   1686: /*   } */
                   1687: /*      u[p]='\0'; */
1.126     brouard  1688: 
1.137     brouard  1689: /*    for(j=0; j<= lg; j++) { */
                   1690: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1691: /*   } */
                   1692: /* } */
1.126     brouard  1693: 
1.160     brouard  1694: #ifdef _WIN32
                   1695: char * strsep(char **pp, const char *delim)
                   1696: {
                   1697:   char *p, *q;
                   1698:          
                   1699:   if ((p = *pp) == NULL)
                   1700:     return 0;
                   1701:   if ((q = strpbrk (p, delim)) != NULL)
                   1702:   {
                   1703:     *pp = q + 1;
                   1704:     *q = '\0';
                   1705:   }
                   1706:   else
                   1707:     *pp = 0;
                   1708:   return p;
                   1709: }
                   1710: #endif
                   1711: 
1.126     brouard  1712: /********************** nrerror ********************/
                   1713: 
                   1714: void nrerror(char error_text[])
                   1715: {
                   1716:   fprintf(stderr,"ERREUR ...\n");
                   1717:   fprintf(stderr,"%s\n",error_text);
                   1718:   exit(EXIT_FAILURE);
                   1719: }
                   1720: /*********************** vector *******************/
                   1721: double *vector(int nl, int nh)
                   1722: {
                   1723:   double *v;
                   1724:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1725:   if (!v) nrerror("allocation failure in vector");
                   1726:   return v-nl+NR_END;
                   1727: }
                   1728: 
                   1729: /************************ free vector ******************/
                   1730: void free_vector(double*v, int nl, int nh)
                   1731: {
                   1732:   free((FREE_ARG)(v+nl-NR_END));
                   1733: }
                   1734: 
                   1735: /************************ivector *******************************/
                   1736: int *ivector(long nl,long nh)
                   1737: {
                   1738:   int *v;
                   1739:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1740:   if (!v) nrerror("allocation failure in ivector");
                   1741:   return v-nl+NR_END;
                   1742: }
                   1743: 
                   1744: /******************free ivector **************************/
                   1745: void free_ivector(int *v, long nl, long nh)
                   1746: {
                   1747:   free((FREE_ARG)(v+nl-NR_END));
                   1748: }
                   1749: 
                   1750: /************************lvector *******************************/
                   1751: long *lvector(long nl,long nh)
                   1752: {
                   1753:   long *v;
                   1754:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1755:   if (!v) nrerror("allocation failure in ivector");
                   1756:   return v-nl+NR_END;
                   1757: }
                   1758: 
                   1759: /******************free lvector **************************/
                   1760: void free_lvector(long *v, long nl, long nh)
                   1761: {
                   1762:   free((FREE_ARG)(v+nl-NR_END));
                   1763: }
                   1764: 
                   1765: /******************* imatrix *******************************/
                   1766: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1767:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1768: { 
                   1769:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1770:   int **m; 
                   1771:   
                   1772:   /* allocate pointers to rows */ 
                   1773:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1774:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1775:   m += NR_END; 
                   1776:   m -= nrl; 
                   1777:   
                   1778:   
                   1779:   /* allocate rows and set pointers to them */ 
                   1780:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1781:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1782:   m[nrl] += NR_END; 
                   1783:   m[nrl] -= ncl; 
                   1784:   
                   1785:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1786:   
                   1787:   /* return pointer to array of pointers to rows */ 
                   1788:   return m; 
                   1789: } 
                   1790: 
                   1791: /****************** free_imatrix *************************/
                   1792: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1793:       int **m;
                   1794:       long nch,ncl,nrh,nrl; 
                   1795:      /* free an int matrix allocated by imatrix() */ 
                   1796: { 
                   1797:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1798:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1799: } 
                   1800: 
                   1801: /******************* matrix *******************************/
                   1802: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1803: {
                   1804:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1805:   double **m;
                   1806: 
                   1807:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1808:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1809:   m += NR_END;
                   1810:   m -= nrl;
                   1811: 
                   1812:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1813:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1814:   m[nrl] += NR_END;
                   1815:   m[nrl] -= ncl;
                   1816: 
                   1817:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1818:   return m;
1.145     brouard  1819:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1820: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1821: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1822:    */
                   1823: }
                   1824: 
                   1825: /*************************free matrix ************************/
                   1826: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1827: {
                   1828:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1829:   free((FREE_ARG)(m+nrl-NR_END));
                   1830: }
                   1831: 
                   1832: /******************* ma3x *******************************/
                   1833: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1834: {
                   1835:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1836:   double ***m;
                   1837: 
                   1838:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1839:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1840:   m += NR_END;
                   1841:   m -= nrl;
                   1842: 
                   1843:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1844:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1845:   m[nrl] += NR_END;
                   1846:   m[nrl] -= ncl;
                   1847: 
                   1848:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1849: 
                   1850:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1851:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1852:   m[nrl][ncl] += NR_END;
                   1853:   m[nrl][ncl] -= nll;
                   1854:   for (j=ncl+1; j<=nch; j++) 
                   1855:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1856:   
                   1857:   for (i=nrl+1; i<=nrh; i++) {
                   1858:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1859:     for (j=ncl+1; j<=nch; j++) 
                   1860:       m[i][j]=m[i][j-1]+nlay;
                   1861:   }
                   1862:   return m; 
                   1863:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1864:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1865:   */
                   1866: }
                   1867: 
                   1868: /*************************free ma3x ************************/
                   1869: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1870: {
                   1871:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1872:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1873:   free((FREE_ARG)(m+nrl-NR_END));
                   1874: }
                   1875: 
                   1876: /*************** function subdirf ***********/
                   1877: char *subdirf(char fileres[])
                   1878: {
                   1879:   /* Caution optionfilefiname is hidden */
                   1880:   strcpy(tmpout,optionfilefiname);
                   1881:   strcat(tmpout,"/"); /* Add to the right */
                   1882:   strcat(tmpout,fileres);
                   1883:   return tmpout;
                   1884: }
                   1885: 
                   1886: /*************** function subdirf2 ***********/
                   1887: char *subdirf2(char fileres[], char *preop)
                   1888: {
1.314     brouard  1889:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1890:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1891:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1892:   /* Caution optionfilefiname is hidden */
                   1893:   strcpy(tmpout,optionfilefiname);
                   1894:   strcat(tmpout,"/");
                   1895:   strcat(tmpout,preop);
                   1896:   strcat(tmpout,fileres);
                   1897:   return tmpout;
                   1898: }
                   1899: 
                   1900: /*************** function subdirf3 ***********/
                   1901: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1902: {
                   1903:   
                   1904:   /* Caution optionfilefiname is hidden */
                   1905:   strcpy(tmpout,optionfilefiname);
                   1906:   strcat(tmpout,"/");
                   1907:   strcat(tmpout,preop);
                   1908:   strcat(tmpout,preop2);
                   1909:   strcat(tmpout,fileres);
                   1910:   return tmpout;
                   1911: }
1.213     brouard  1912:  
                   1913: /*************** function subdirfext ***********/
                   1914: char *subdirfext(char fileres[], char *preop, char *postop)
                   1915: {
                   1916:   
                   1917:   strcpy(tmpout,preop);
                   1918:   strcat(tmpout,fileres);
                   1919:   strcat(tmpout,postop);
                   1920:   return tmpout;
                   1921: }
1.126     brouard  1922: 
1.213     brouard  1923: /*************** function subdirfext3 ***********/
                   1924: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1925: {
                   1926:   
                   1927:   /* Caution optionfilefiname is hidden */
                   1928:   strcpy(tmpout,optionfilefiname);
                   1929:   strcat(tmpout,"/");
                   1930:   strcat(tmpout,preop);
                   1931:   strcat(tmpout,fileres);
                   1932:   strcat(tmpout,postop);
                   1933:   return tmpout;
                   1934: }
                   1935:  
1.162     brouard  1936: char *asc_diff_time(long time_sec, char ascdiff[])
                   1937: {
                   1938:   long sec_left, days, hours, minutes;
                   1939:   days = (time_sec) / (60*60*24);
                   1940:   sec_left = (time_sec) % (60*60*24);
                   1941:   hours = (sec_left) / (60*60) ;
                   1942:   sec_left = (sec_left) %(60*60);
                   1943:   minutes = (sec_left) /60;
                   1944:   sec_left = (sec_left) % (60);
                   1945:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1946:   return ascdiff;
                   1947: }
                   1948: 
1.126     brouard  1949: /***************** f1dim *************************/
                   1950: extern int ncom; 
                   1951: extern double *pcom,*xicom;
                   1952: extern double (*nrfunc)(double []); 
                   1953:  
                   1954: double f1dim(double x) 
                   1955: { 
                   1956:   int j; 
                   1957:   double f;
                   1958:   double *xt; 
                   1959:  
                   1960:   xt=vector(1,ncom); 
                   1961:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1962:   f=(*nrfunc)(xt); 
                   1963:   free_vector(xt,1,ncom); 
                   1964:   return f; 
                   1965: } 
                   1966: 
                   1967: /*****************brent *************************/
                   1968: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1969: {
                   1970:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1971:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1972:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1973:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1974:    * returned function value. 
                   1975:   */
1.126     brouard  1976:   int iter; 
                   1977:   double a,b,d,etemp;
1.159     brouard  1978:   double fu=0,fv,fw,fx;
1.164     brouard  1979:   double ftemp=0.;
1.126     brouard  1980:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1981:   double e=0.0; 
                   1982:  
                   1983:   a=(ax < cx ? ax : cx); 
                   1984:   b=(ax > cx ? ax : cx); 
                   1985:   x=w=v=bx; 
                   1986:   fw=fv=fx=(*f)(x); 
                   1987:   for (iter=1;iter<=ITMAX;iter++) { 
                   1988:     xm=0.5*(a+b); 
                   1989:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1990:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1991:     printf(".");fflush(stdout);
                   1992:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1993: #ifdef DEBUGBRENT
1.126     brouard  1994:     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);
                   1995:     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);
                   1996:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1997: #endif
                   1998:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1999:       *xmin=x; 
                   2000:       return fx; 
                   2001:     } 
                   2002:     ftemp=fu;
                   2003:     if (fabs(e) > tol1) { 
                   2004:       r=(x-w)*(fx-fv); 
                   2005:       q=(x-v)*(fx-fw); 
                   2006:       p=(x-v)*q-(x-w)*r; 
                   2007:       q=2.0*(q-r); 
                   2008:       if (q > 0.0) p = -p; 
                   2009:       q=fabs(q); 
                   2010:       etemp=e; 
                   2011:       e=d; 
                   2012:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2013:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2014:       else { 
1.224     brouard  2015:                                d=p/q; 
                   2016:                                u=x+d; 
                   2017:                                if (u-a < tol2 || b-u < tol2) 
                   2018:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2019:       } 
                   2020:     } else { 
                   2021:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2022:     } 
                   2023:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2024:     fu=(*f)(u); 
                   2025:     if (fu <= fx) { 
                   2026:       if (u >= x) a=x; else b=x; 
                   2027:       SHFT(v,w,x,u) 
1.183     brouard  2028:       SHFT(fv,fw,fx,fu) 
                   2029:     } else { 
                   2030:       if (u < x) a=u; else b=u; 
                   2031:       if (fu <= fw || w == x) { 
1.224     brouard  2032:                                v=w; 
                   2033:                                w=u; 
                   2034:                                fv=fw; 
                   2035:                                fw=fu; 
1.183     brouard  2036:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2037:                                v=u; 
                   2038:                                fv=fu; 
1.183     brouard  2039:       } 
                   2040:     } 
1.126     brouard  2041:   } 
                   2042:   nrerror("Too many iterations in brent"); 
                   2043:   *xmin=x; 
                   2044:   return fx; 
                   2045: } 
                   2046: 
                   2047: /****************** mnbrak ***********************/
                   2048: 
                   2049: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2050:            double (*func)(double)) 
1.183     brouard  2051: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2052: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2053: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2054: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2055:    */
1.126     brouard  2056:   double ulim,u,r,q, dum;
                   2057:   double fu; 
1.187     brouard  2058: 
                   2059:   double scale=10.;
                   2060:   int iterscale=0;
                   2061: 
                   2062:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2063:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2064: 
                   2065: 
                   2066:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2067:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2068:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2069:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2070:   /* } */
                   2071: 
1.126     brouard  2072:   if (*fb > *fa) { 
                   2073:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2074:     SHFT(dum,*fb,*fa,dum) 
                   2075:   } 
1.126     brouard  2076:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2077:   *fc=(*func)(*cx); 
1.183     brouard  2078: #ifdef DEBUG
1.224     brouard  2079:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2080:   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  2081: #endif
1.224     brouard  2082:   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  2083:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2084:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2085:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2086:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2087:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2088:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2089:       fu=(*func)(u); 
1.163     brouard  2090: #ifdef DEBUG
                   2091:       /* f(x)=A(x-u)**2+f(u) */
                   2092:       double A, fparabu; 
                   2093:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2094:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2095:       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);
                   2096:       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  2097:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2098:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2099:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2100:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2101: #endif 
1.184     brouard  2102: #ifdef MNBRAKORIGINAL
1.183     brouard  2103: #else
1.191     brouard  2104: /*       if (fu > *fc) { */
                   2105: /* #ifdef DEBUG */
                   2106: /*       printf("mnbrak4  fu > fc \n"); */
                   2107: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2108: /* #endif */
                   2109: /*     /\* 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 *\\/  *\/ */
                   2110: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2111: /*     dum=u; /\* Shifting c and u *\/ */
                   2112: /*     u = *cx; */
                   2113: /*     *cx = dum; */
                   2114: /*     dum = fu; */
                   2115: /*     fu = *fc; */
                   2116: /*     *fc =dum; */
                   2117: /*       } else { /\* end *\/ */
                   2118: /* #ifdef DEBUG */
                   2119: /*       printf("mnbrak3  fu < fc \n"); */
                   2120: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2121: /* #endif */
                   2122: /*     dum=u; /\* Shifting c and u *\/ */
                   2123: /*     u = *cx; */
                   2124: /*     *cx = dum; */
                   2125: /*     dum = fu; */
                   2126: /*     fu = *fc; */
                   2127: /*     *fc =dum; */
                   2128: /*       } */
1.224     brouard  2129: #ifdef DEBUGMNBRAK
                   2130:                 double A, fparabu; 
                   2131:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2132:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2133:      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);
                   2134:      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  2135: #endif
1.191     brouard  2136:       dum=u; /* Shifting c and u */
                   2137:       u = *cx;
                   2138:       *cx = dum;
                   2139:       dum = fu;
                   2140:       fu = *fc;
                   2141:       *fc =dum;
1.183     brouard  2142: #endif
1.162     brouard  2143:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2144: #ifdef DEBUG
1.224     brouard  2145:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2146:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2147: #endif
1.126     brouard  2148:       fu=(*func)(u); 
                   2149:       if (fu < *fc) { 
1.183     brouard  2150: #ifdef DEBUG
1.224     brouard  2151:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2152:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2153: #endif
                   2154:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2155:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2156: #ifdef DEBUG
                   2157:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2158: #endif
                   2159:       } 
1.162     brouard  2160:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2161: #ifdef DEBUG
1.224     brouard  2162:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2163:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2164: #endif
1.126     brouard  2165:       u=ulim; 
                   2166:       fu=(*func)(u); 
1.183     brouard  2167:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2168: #ifdef DEBUG
1.224     brouard  2169:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2170:       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  2171: #endif
1.126     brouard  2172:       u=(*cx)+GOLD*(*cx-*bx); 
                   2173:       fu=(*func)(u); 
1.224     brouard  2174: #ifdef DEBUG
                   2175:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2176:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2177: #endif
1.183     brouard  2178:     } /* end tests */
1.126     brouard  2179:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2180:     SHFT(*fa,*fb,*fc,fu) 
                   2181: #ifdef DEBUG
1.224     brouard  2182:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2183:       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  2184: #endif
                   2185:   } /* 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  2186: } 
                   2187: 
                   2188: /*************** linmin ************************/
1.162     brouard  2189: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2190: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2191: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2192: the value of func at the returned location p . This is actually all accomplished by calling the
                   2193: routines mnbrak and brent .*/
1.126     brouard  2194: int ncom; 
                   2195: double *pcom,*xicom;
                   2196: double (*nrfunc)(double []); 
                   2197:  
1.224     brouard  2198: #ifdef LINMINORIGINAL
1.126     brouard  2199: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2200: #else
                   2201: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2202: #endif
1.126     brouard  2203: { 
                   2204:   double brent(double ax, double bx, double cx, 
                   2205:               double (*f)(double), double tol, double *xmin); 
                   2206:   double f1dim(double x); 
                   2207:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2208:              double *fc, double (*func)(double)); 
                   2209:   int j; 
                   2210:   double xx,xmin,bx,ax; 
                   2211:   double fx,fb,fa;
1.187     brouard  2212: 
1.203     brouard  2213: #ifdef LINMINORIGINAL
                   2214: #else
                   2215:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2216: #endif
                   2217:   
1.126     brouard  2218:   ncom=n; 
                   2219:   pcom=vector(1,n); 
                   2220:   xicom=vector(1,n); 
                   2221:   nrfunc=func; 
                   2222:   for (j=1;j<=n;j++) { 
                   2223:     pcom[j]=p[j]; 
1.202     brouard  2224:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2225:   } 
1.187     brouard  2226: 
1.203     brouard  2227: #ifdef LINMINORIGINAL
                   2228:   xx=1.;
                   2229: #else
                   2230:   axs=0.0;
                   2231:   xxs=1.;
                   2232:   do{
                   2233:     xx= xxs;
                   2234: #endif
1.187     brouard  2235:     ax=0.;
                   2236:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2237:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2238:     /* 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))   */
                   2239:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2240:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2241:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2242:     /* 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  2243: #ifdef LINMINORIGINAL
                   2244: #else
                   2245:     if (fx != fx){
1.224     brouard  2246:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2247:                        printf("|");
                   2248:                        fprintf(ficlog,"|");
1.203     brouard  2249: #ifdef DEBUGLINMIN
1.224     brouard  2250:                        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  2251: #endif
                   2252:     }
1.224     brouard  2253:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2254: #endif
                   2255:   
1.191     brouard  2256: #ifdef DEBUGLINMIN
                   2257:   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  2258:   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  2259: #endif
1.224     brouard  2260: #ifdef LINMINORIGINAL
                   2261: #else
1.317   ! brouard  2262:   if(fb == fx){ /* Flat function in the direction */
        !          2263:     xmin=xx;
1.224     brouard  2264:     *flat=1;
1.317   ! brouard  2265:   }else{
1.224     brouard  2266:     *flat=0;
                   2267: #endif
                   2268:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2269:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2270:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2271:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2272:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2273:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2274: #ifdef DEBUG
1.224     brouard  2275:   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);
                   2276:   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);
                   2277: #endif
                   2278: #ifdef LINMINORIGINAL
                   2279: #else
                   2280:                        }
1.126     brouard  2281: #endif
1.191     brouard  2282: #ifdef DEBUGLINMIN
                   2283:   printf("linmin end ");
1.202     brouard  2284:   fprintf(ficlog,"linmin end ");
1.191     brouard  2285: #endif
1.126     brouard  2286:   for (j=1;j<=n;j++) { 
1.203     brouard  2287: #ifdef LINMINORIGINAL
                   2288:     xi[j] *= xmin; 
                   2289: #else
                   2290: #ifdef DEBUGLINMIN
                   2291:     if(xxs <1.0)
                   2292:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2293: #endif
                   2294:     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) */
                   2295: #ifdef DEBUGLINMIN
                   2296:     if(xxs <1.0)
                   2297:       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 );
                   2298: #endif
                   2299: #endif
1.187     brouard  2300:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2301:   } 
1.191     brouard  2302: #ifdef DEBUGLINMIN
1.203     brouard  2303:   printf("\n");
1.191     brouard  2304:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2305:   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  2306:   for (j=1;j<=n;j++) { 
1.202     brouard  2307:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2308:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2309:     if(j % ncovmodel == 0){
1.191     brouard  2310:       printf("\n");
1.202     brouard  2311:       fprintf(ficlog,"\n");
                   2312:     }
1.191     brouard  2313:   }
1.203     brouard  2314: #else
1.191     brouard  2315: #endif
1.126     brouard  2316:   free_vector(xicom,1,n); 
                   2317:   free_vector(pcom,1,n); 
                   2318: } 
                   2319: 
                   2320: 
                   2321: /*************** powell ************************/
1.162     brouard  2322: /*
1.317   ! brouard  2323: Minimization of a function func of n variables. Input consists in an initial starting point
        !          2324: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
        !          2325: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
        !          2326: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2327: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2328: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2329:  */
1.224     brouard  2330: #ifdef LINMINORIGINAL
                   2331: #else
                   2332:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2333:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2334: #endif
1.126     brouard  2335: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2336:            double (*func)(double [])) 
                   2337: { 
1.224     brouard  2338: #ifdef LINMINORIGINAL
                   2339:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2340:              double (*func)(double [])); 
1.224     brouard  2341: #else 
1.241     brouard  2342:  void linmin(double p[], double xi[], int n, double *fret,
                   2343:             double (*func)(double []),int *flat); 
1.224     brouard  2344: #endif
1.239     brouard  2345:  int i,ibig,j,jk,k; 
1.126     brouard  2346:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2347:   double directest;
1.126     brouard  2348:   double fp,fptt;
                   2349:   double *xits;
                   2350:   int niterf, itmp;
1.224     brouard  2351: #ifdef LINMINORIGINAL
                   2352: #else
                   2353: 
                   2354:   flatdir=ivector(1,n); 
                   2355:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2356: #endif
1.126     brouard  2357: 
                   2358:   pt=vector(1,n); 
                   2359:   ptt=vector(1,n); 
                   2360:   xit=vector(1,n); 
                   2361:   xits=vector(1,n); 
                   2362:   *fret=(*func)(p); 
                   2363:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2364:   rcurr_time = time(NULL);  
1.126     brouard  2365:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2366:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2367:     ibig=0; 
                   2368:     del=0.0; 
1.157     brouard  2369:     rlast_time=rcurr_time;
                   2370:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2371:     rcurr_time = time(NULL);  
                   2372:     curr_time = *localtime(&rcurr_time);
                   2373:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2374:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2375: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2376:     for (i=1;i<=n;i++) {
1.126     brouard  2377:       fprintf(ficrespow," %.12lf", p[i]);
                   2378:     }
1.239     brouard  2379:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2380:     printf("\n#model=  1      +     age ");
                   2381:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2382:     if(nagesqr==1){
1.241     brouard  2383:        printf("  + age*age  ");
                   2384:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2385:     }
                   2386:     for(j=1;j <=ncovmodel-2;j++){
                   2387:       if(Typevar[j]==0) {
                   2388:        printf("  +      V%d  ",Tvar[j]);
                   2389:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2390:       }else if(Typevar[j]==1) {
                   2391:        printf("  +    V%d*age ",Tvar[j]);
                   2392:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2393:       }else if(Typevar[j]==2) {
                   2394:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2395:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2396:       }
                   2397:     }
1.126     brouard  2398:     printf("\n");
1.239     brouard  2399: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2400: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2401:     fprintf(ficlog,"\n");
1.239     brouard  2402:     for(i=1,jk=1; i <=nlstate; i++){
                   2403:       for(k=1; k <=(nlstate+ndeath); k++){
                   2404:        if (k != i) {
                   2405:          printf("%d%d ",i,k);
                   2406:          fprintf(ficlog,"%d%d ",i,k);
                   2407:          for(j=1; j <=ncovmodel; j++){
                   2408:            printf("%12.7f ",p[jk]);
                   2409:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2410:            jk++; 
                   2411:          }
                   2412:          printf("\n");
                   2413:          fprintf(ficlog,"\n");
                   2414:        }
                   2415:       }
                   2416:     }
1.241     brouard  2417:     if(*iter <=3 && *iter >1){
1.157     brouard  2418:       tml = *localtime(&rcurr_time);
                   2419:       strcpy(strcurr,asctime(&tml));
                   2420:       rforecast_time=rcurr_time; 
1.126     brouard  2421:       itmp = strlen(strcurr);
                   2422:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2423:        strcurr[itmp-1]='\0';
1.162     brouard  2424:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2425:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2426:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2427:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2428:        forecast_time = *localtime(&rforecast_time);
                   2429:        strcpy(strfor,asctime(&forecast_time));
                   2430:        itmp = strlen(strfor);
                   2431:        if(strfor[itmp-1]=='\n')
                   2432:          strfor[itmp-1]='\0';
                   2433:        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);
                   2434:        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  2435:       }
                   2436:     }
1.187     brouard  2437:     for (i=1;i<=n;i++) { /* For each direction i */
                   2438:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2439:       fptt=(*fret); 
                   2440: #ifdef DEBUG
1.203     brouard  2441:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2442:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2443: #endif
1.203     brouard  2444:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2445:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2446: #ifdef LINMINORIGINAL
1.188     brouard  2447:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2448: #else
                   2449:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2450:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2451: #endif
                   2452:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2453:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2454:                                /* because that direction will be replaced unless the gain del is small */
                   2455:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2456:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2457:                                /* with the new direction. */
                   2458:                                del=fabs(fptt-(*fret)); 
                   2459:                                ibig=i; 
1.126     brouard  2460:       } 
                   2461: #ifdef DEBUG
                   2462:       printf("%d %.12e",i,(*fret));
                   2463:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2464:       for (j=1;j<=n;j++) {
1.224     brouard  2465:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2466:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2467:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2468:       }
                   2469:       for(j=1;j<=n;j++) {
1.225     brouard  2470:                                printf(" p(%d)=%.12e",j,p[j]);
                   2471:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2472:       }
                   2473:       printf("\n");
                   2474:       fprintf(ficlog,"\n");
                   2475: #endif
1.187     brouard  2476:     } /* end loop on each direction i */
                   2477:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2478:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2479:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2480:       for(j=1;j<=n;j++) {
1.302     brouard  2481:        if(flatdir[j] >0){
                   2482:          printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2483:          fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2484:        }
                   2485:        /* printf("\n"); */
                   2486:        /* fprintf(ficlog,"\n"); */
                   2487:       }
1.243     brouard  2488:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2489:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2490:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2491:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2492:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2493:       /* decreased of more than 3.84  */
                   2494:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2495:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2496:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2497:                        
1.188     brouard  2498:       /* Starting the program with initial values given by a former maximization will simply change */
                   2499:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2500:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2501:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2502: #ifdef DEBUG
                   2503:       int k[2],l;
                   2504:       k[0]=1;
                   2505:       k[1]=-1;
                   2506:       printf("Max: %.12e",(*func)(p));
                   2507:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2508:       for (j=1;j<=n;j++) {
                   2509:        printf(" %.12e",p[j]);
                   2510:        fprintf(ficlog," %.12e",p[j]);
                   2511:       }
                   2512:       printf("\n");
                   2513:       fprintf(ficlog,"\n");
                   2514:       for(l=0;l<=1;l++) {
                   2515:        for (j=1;j<=n;j++) {
                   2516:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2517:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2518:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2519:        }
                   2520:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2521:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2522:       }
                   2523: #endif
                   2524: 
1.224     brouard  2525: #ifdef LINMINORIGINAL
                   2526: #else
                   2527:       free_ivector(flatdir,1,n); 
                   2528: #endif
1.126     brouard  2529:       free_vector(xit,1,n); 
                   2530:       free_vector(xits,1,n); 
                   2531:       free_vector(ptt,1,n); 
                   2532:       free_vector(pt,1,n); 
                   2533:       return; 
1.192     brouard  2534:     } /* enough precision */ 
1.240     brouard  2535:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2536:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2537:       ptt[j]=2.0*p[j]-pt[j]; 
                   2538:       xit[j]=p[j]-pt[j]; 
                   2539:       pt[j]=p[j]; 
                   2540:     } 
1.181     brouard  2541:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2542: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2543:                if (*iter <=4) {
1.225     brouard  2544: #else
                   2545: #endif
1.224     brouard  2546: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2547: #else
1.161     brouard  2548:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2549: #endif
1.162     brouard  2550:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2551:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2552:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2553:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2554:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2555:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2556:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2557:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2558:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2559:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2560:       /* mu² and del² are equal when f3=f1 */
                   2561:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2562:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2563:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2564:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2565: #ifdef NRCORIGINAL
                   2566:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2567: #else
                   2568:       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  2569:       t= t- del*SQR(fp-fptt);
1.183     brouard  2570: #endif
1.202     brouard  2571:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2572: #ifdef DEBUG
1.181     brouard  2573:       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);
                   2574:       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  2575:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2576:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2577:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2578:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2579:       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);
                   2580:       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);
                   2581: #endif
1.183     brouard  2582: #ifdef POWELLORIGINAL
                   2583:       if (t < 0.0) { /* Then we use it for new direction */
                   2584: #else
1.182     brouard  2585:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2586:                                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  2587:         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  2588:         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  2589:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2590:       } 
1.181     brouard  2591:       if (directest < 0.0) { /* Then we use it for new direction */
                   2592: #endif
1.191     brouard  2593: #ifdef DEBUGLINMIN
1.234     brouard  2594:        printf("Before linmin in direction P%d-P0\n",n);
                   2595:        for (j=1;j<=n;j++) {
                   2596:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2597:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2598:          if(j % ncovmodel == 0){
                   2599:            printf("\n");
                   2600:            fprintf(ficlog,"\n");
                   2601:          }
                   2602:        }
1.224     brouard  2603: #endif
                   2604: #ifdef LINMINORIGINAL
1.234     brouard  2605:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2606: #else
1.234     brouard  2607:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2608:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2609: #endif
1.234     brouard  2610:        
1.191     brouard  2611: #ifdef DEBUGLINMIN
1.234     brouard  2612:        for (j=1;j<=n;j++) { 
                   2613:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2614:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2615:          if(j % ncovmodel == 0){
                   2616:            printf("\n");
                   2617:            fprintf(ficlog,"\n");
                   2618:          }
                   2619:        }
1.224     brouard  2620: #endif
1.234     brouard  2621:        for (j=1;j<=n;j++) { 
                   2622:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2623:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2624:        }
1.224     brouard  2625: #ifdef LINMINORIGINAL
                   2626: #else
1.234     brouard  2627:        for (j=1, flatd=0;j<=n;j++) {
                   2628:          if(flatdir[j]>0)
                   2629:            flatd++;
                   2630:        }
                   2631:        if(flatd >0){
1.255     brouard  2632:          printf("%d flat directions: ",flatd);
                   2633:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2634:          for (j=1;j<=n;j++) { 
                   2635:            if(flatdir[j]>0){
                   2636:              printf("%d ",j);
                   2637:              fprintf(ficlog,"%d ",j);
                   2638:            }
                   2639:          }
                   2640:          printf("\n");
                   2641:          fprintf(ficlog,"\n");
                   2642:        }
1.191     brouard  2643: #endif
1.234     brouard  2644:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2645:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2646:        
1.126     brouard  2647: #ifdef DEBUG
1.234     brouard  2648:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2649:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2650:        for(j=1;j<=n;j++){
                   2651:          printf(" %lf",xit[j]);
                   2652:          fprintf(ficlog," %lf",xit[j]);
                   2653:        }
                   2654:        printf("\n");
                   2655:        fprintf(ficlog,"\n");
1.126     brouard  2656: #endif
1.192     brouard  2657:       } /* end of t or directest negative */
1.224     brouard  2658: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2659: #else
1.234     brouard  2660:       } /* end if (fptt < fp)  */
1.192     brouard  2661: #endif
1.225     brouard  2662: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2663:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2664: #else
1.224     brouard  2665: #endif
1.234     brouard  2666:                } /* loop iteration */ 
1.126     brouard  2667: } 
1.234     brouard  2668:   
1.126     brouard  2669: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2670:   
1.235     brouard  2671:   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  2672:   {
1.279     brouard  2673:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2674:      *   (and selected quantitative values in nres)
                   2675:      *  by left multiplying the unit
                   2676:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2677:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2678:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2679:      * or prevalence in state 1, prevalence in state 2, 0
                   2680:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2681:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2682:      * Output is prlim.
                   2683:      * Initial matrix pimij 
                   2684:      */
1.206     brouard  2685:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2686:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2687:   /*  0,                   0                  , 1} */
                   2688:   /*
                   2689:    * and after some iteration: */
                   2690:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2691:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2692:   /*  0,                   0                  , 1} */
                   2693:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2694:   /* {0.51571254859325999, 0.4842874514067399, */
                   2695:   /*  0.51326036147820708, 0.48673963852179264} */
                   2696:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2697:     
1.126     brouard  2698:   int i, ii,j,k;
1.209     brouard  2699:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2700:   /* double **matprod2(); */ /* test */
1.218     brouard  2701:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2702:   double **newm;
1.209     brouard  2703:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2704:   int ncvloop=0;
1.288     brouard  2705:   int first=0;
1.169     brouard  2706:   
1.209     brouard  2707:   min=vector(1,nlstate);
                   2708:   max=vector(1,nlstate);
                   2709:   meandiff=vector(1,nlstate);
                   2710: 
1.218     brouard  2711:        /* Starting with matrix unity */
1.126     brouard  2712:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2713:     for (j=1;j<=nlstate+ndeath;j++){
                   2714:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2715:     }
1.169     brouard  2716:   
                   2717:   cov[1]=1.;
                   2718:   
                   2719:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2720:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2721:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2722:     ncvloop++;
1.126     brouard  2723:     newm=savm;
                   2724:     /* Covariates have to be included here again */
1.138     brouard  2725:     cov[2]=agefin;
1.187     brouard  2726:     if(nagesqr==1)
                   2727:       cov[3]= agefin*agefin;;
1.234     brouard  2728:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2729:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2730:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2731:       /* 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  2732:     }
                   2733:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2734:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2735:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2736:       /* 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  2737:     }
1.237     brouard  2738:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2739:       if(Dummy[Tvar[Tage[k]]]){
                   2740:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2741:       } else{
1.235     brouard  2742:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2743:       }
1.235     brouard  2744:       /* 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  2745:     }
1.237     brouard  2746:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2747:       /* 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  2748:       if(Dummy[Tvard[k][1]==0]){
                   2749:        if(Dummy[Tvard[k][2]==0]){
                   2750:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2751:        }else{
                   2752:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2753:        }
                   2754:       }else{
                   2755:        if(Dummy[Tvard[k][2]==0]){
                   2756:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2757:        }else{
                   2758:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2759:        }
                   2760:       }
1.234     brouard  2761:     }
1.138     brouard  2762:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2763:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2764:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2765:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2766:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2767:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2768:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2769:     
1.126     brouard  2770:     savm=oldm;
                   2771:     oldm=newm;
1.209     brouard  2772: 
                   2773:     for(j=1; j<=nlstate; j++){
                   2774:       max[j]=0.;
                   2775:       min[j]=1.;
                   2776:     }
                   2777:     for(i=1;i<=nlstate;i++){
                   2778:       sumnew=0;
                   2779:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2780:       for(j=1; j<=nlstate; j++){ 
                   2781:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2782:        max[j]=FMAX(max[j],prlim[i][j]);
                   2783:        min[j]=FMIN(min[j],prlim[i][j]);
                   2784:       }
                   2785:     }
                   2786: 
1.126     brouard  2787:     maxmax=0.;
1.209     brouard  2788:     for(j=1; j<=nlstate; j++){
                   2789:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2790:       maxmax=FMAX(maxmax,meandiff[j]);
                   2791:       /* 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  2792:     } /* j loop */
1.203     brouard  2793:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2794:     /* 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  2795:     if(maxmax < ftolpl){
1.209     brouard  2796:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2797:       free_vector(min,1,nlstate);
                   2798:       free_vector(max,1,nlstate);
                   2799:       free_vector(meandiff,1,nlstate);
1.126     brouard  2800:       return prlim;
                   2801:     }
1.288     brouard  2802:   } /* agefin loop */
1.208     brouard  2803:     /* After some age loop it doesn't converge */
1.288     brouard  2804:   if(!first){
                   2805:     first=1;
                   2806:     printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d). Others in log file only...\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
1.317   ! brouard  2807:     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);
        !          2808:   }else if (first >=1 && first <10){
        !          2809:     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);
        !          2810:     first++;
        !          2811:   }else if (first ==10){
        !          2812:     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);
        !          2813:     printf("Warning: the stable prevalence dit not converge. This warning came too often, IMaCh will stop notifying, even in its log file. Look at the graphs to appreciate the non convergence.\n");
        !          2814:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
        !          2815:     first++;
1.288     brouard  2816:   }
                   2817: 
1.209     brouard  2818:   /* 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); */
                   2819:   free_vector(min,1,nlstate);
                   2820:   free_vector(max,1,nlstate);
                   2821:   free_vector(meandiff,1,nlstate);
1.208     brouard  2822:   
1.169     brouard  2823:   return prlim; /* should not reach here */
1.126     brouard  2824: }
                   2825: 
1.217     brouard  2826: 
                   2827:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2828: 
1.218     brouard  2829:  /* 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) */
                   2830:  /* 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  2831:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2832: {
1.264     brouard  2833:   /* 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  2834:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2835:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2836:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2837:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2838:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2839:   /* Initial matrix pimij */
                   2840:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2841:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2842:   /*  0,                   0                  , 1} */
                   2843:   /*
                   2844:    * and after some iteration: */
                   2845:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2846:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2847:   /*  0,                   0                  , 1} */
                   2848:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2849:   /* {0.51571254859325999, 0.4842874514067399, */
                   2850:   /*  0.51326036147820708, 0.48673963852179264} */
                   2851:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2852: 
                   2853:   int i, ii,j,k;
1.247     brouard  2854:   int first=0;
1.217     brouard  2855:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2856:   /* double **matprod2(); */ /* test */
                   2857:   double **out, cov[NCOVMAX+1], **bmij();
                   2858:   double **newm;
1.218     brouard  2859:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2860:   double        **oldm, **savm;  /* for use */
                   2861: 
1.217     brouard  2862:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2863:   int ncvloop=0;
                   2864:   
                   2865:   min=vector(1,nlstate);
                   2866:   max=vector(1,nlstate);
                   2867:   meandiff=vector(1,nlstate);
                   2868: 
1.266     brouard  2869:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2870:   oldm=oldms; savm=savms;
                   2871:   
                   2872:   /* Starting with matrix unity */
                   2873:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2874:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2875:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2876:     }
                   2877:   
                   2878:   cov[1]=1.;
                   2879:   
                   2880:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2881:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2882:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2883:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2884:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2885:     ncvloop++;
1.218     brouard  2886:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2887:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2888:     /* Covariates have to be included here again */
                   2889:     cov[2]=agefin;
                   2890:     if(nagesqr==1)
                   2891:       cov[3]= agefin*agefin;;
1.242     brouard  2892:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2893:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2894:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2895:       /* 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  2896:     }
                   2897:     /* for (k=1; k<=cptcovn;k++) { */
                   2898:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2899:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2900:     /*   /\* 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])]); *\/ */
                   2901:     /* } */
                   2902:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2903:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2904:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2905:       /* 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]); */
                   2906:     }
                   2907:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2908:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2909:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2910:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2911:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2912:       if(Dummy[Tvar[Tage[k]]]){
                   2913:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2914:       } else{
                   2915:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2916:       }
                   2917:       /* 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]); */
                   2918:     }
                   2919:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2920:       /* 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]); */
                   2921:       if(Dummy[Tvard[k][1]==0]){
                   2922:        if(Dummy[Tvard[k][2]==0]){
                   2923:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2924:        }else{
                   2925:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2926:        }
                   2927:       }else{
                   2928:        if(Dummy[Tvard[k][2]==0]){
                   2929:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2930:        }else{
                   2931:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2932:        }
                   2933:       }
1.217     brouard  2934:     }
                   2935:     
                   2936:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2937:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2938:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2939:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2940:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2941:                /* ij should be linked to the correct index of cov */
                   2942:                /* age and covariate values ij are in 'cov', but we need to pass
                   2943:                 * ij for the observed prevalence at age and status and covariate
                   2944:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2945:                 */
                   2946:     /* 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 *\/ */
                   2947:     /* 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 *\/ */
                   2948:     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  2949:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2950:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2951:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2952:     /*         printf("%d newm= ",i); */
                   2953:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2954:     /*           printf("%f ",newm[i][j]); */
                   2955:     /*         } */
                   2956:     /*         printf("oldm * "); */
                   2957:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2958:     /*           printf("%f ",oldm[i][j]); */
                   2959:     /*         } */
1.268     brouard  2960:     /*         printf(" bmmij "); */
1.266     brouard  2961:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2962:     /*           printf("%f ",pmmij[i][j]); */
                   2963:     /*         } */
                   2964:     /*         printf("\n"); */
                   2965:     /*   } */
                   2966:     /* } */
1.217     brouard  2967:     savm=oldm;
                   2968:     oldm=newm;
1.266     brouard  2969: 
1.217     brouard  2970:     for(j=1; j<=nlstate; j++){
                   2971:       max[j]=0.;
                   2972:       min[j]=1.;
                   2973:     }
                   2974:     for(j=1; j<=nlstate; j++){ 
                   2975:       for(i=1;i<=nlstate;i++){
1.234     brouard  2976:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2977:        bprlim[i][j]= newm[i][j];
                   2978:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2979:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2980:       }
                   2981:     }
1.218     brouard  2982:                
1.217     brouard  2983:     maxmax=0.;
                   2984:     for(i=1; i<=nlstate; i++){
                   2985:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2986:       maxmax=FMAX(maxmax,meandiff[i]);
                   2987:       /* 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  2988:     } /* i loop */
1.217     brouard  2989:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2990:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2991:     if(maxmax < ftolpl){
1.220     brouard  2992:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2993:       free_vector(min,1,nlstate);
                   2994:       free_vector(max,1,nlstate);
                   2995:       free_vector(meandiff,1,nlstate);
                   2996:       return bprlim;
                   2997:     }
1.288     brouard  2998:   } /* agefin loop */
1.217     brouard  2999:     /* After some age loop it doesn't converge */
1.288     brouard  3000:   if(!first){
1.247     brouard  3001:     first=1;
                   3002:     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\
                   3003: 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);
                   3004:   }
                   3005:   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  3006: 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);
                   3007:   /* 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); */
                   3008:   free_vector(min,1,nlstate);
                   3009:   free_vector(max,1,nlstate);
                   3010:   free_vector(meandiff,1,nlstate);
                   3011:   
                   3012:   return bprlim; /* should not reach here */
                   3013: }
                   3014: 
1.126     brouard  3015: /*************** transition probabilities ***************/ 
                   3016: 
                   3017: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3018: {
1.138     brouard  3019:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3020:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3021:      model to the ncovmodel covariates (including constant and age).
                   3022:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3023:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3024:      ncth covariate in the global vector x is given by the formula:
                   3025:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3026:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3027:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3028:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3029:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3030:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3031:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3032:   */
                   3033:   double s1, lnpijopii;
1.126     brouard  3034:   /*double t34;*/
1.164     brouard  3035:   int i,j, nc, ii, jj;
1.126     brouard  3036: 
1.223     brouard  3037:   for(i=1; i<= nlstate; i++){
                   3038:     for(j=1; j<i;j++){
                   3039:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3040:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3041:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3042:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3043:       }
                   3044:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3045:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3046:     }
                   3047:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3048:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3049:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3050:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3051:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3052:       }
                   3053:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3054:     }
                   3055:   }
1.218     brouard  3056:   
1.223     brouard  3057:   for(i=1; i<= nlstate; i++){
                   3058:     s1=0;
                   3059:     for(j=1; j<i; j++){
                   3060:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3061:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3062:     }
                   3063:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3064:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3065:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3066:     }
                   3067:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3068:     ps[i][i]=1./(s1+1.);
                   3069:     /* Computing other pijs */
                   3070:     for(j=1; j<i; j++)
                   3071:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3072:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3073:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3074:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3075:   } /* end i */
1.218     brouard  3076:   
1.223     brouard  3077:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3078:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3079:       ps[ii][jj]=0;
                   3080:       ps[ii][ii]=1;
                   3081:     }
                   3082:   }
1.294     brouard  3083: 
                   3084: 
1.223     brouard  3085:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3086:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3087:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3088:   /*   } */
                   3089:   /*   printf("\n "); */
                   3090:   /* } */
                   3091:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3092:   /*
                   3093:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3094:                goto end;*/
1.266     brouard  3095:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3096: }
                   3097: 
1.218     brouard  3098: /*************** backward transition probabilities ***************/ 
                   3099: 
                   3100:  /* 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 ) */
                   3101: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3102:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3103: {
1.302     brouard  3104:   /* 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  3105:    * 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  3106:    */
1.218     brouard  3107:   int i, ii, j,k;
1.222     brouard  3108:   
                   3109:   double **out, **pmij();
                   3110:   double sumnew=0.;
1.218     brouard  3111:   double agefin;
1.292     brouard  3112:   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  3113:   double **dnewm, **dsavm, **doldm;
                   3114:   double **bbmij;
                   3115:   
1.218     brouard  3116:   doldm=ddoldms; /* global pointers */
1.222     brouard  3117:   dnewm=ddnewms;
                   3118:   dsavm=ddsavms;
                   3119:   
                   3120:   agefin=cov[2];
1.268     brouard  3121:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3122:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3123:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3124:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3125: 
                   3126:   /* P_x */
1.266     brouard  3127:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3128:   /* outputs pmmij which is a stochastic matrix in row */
                   3129: 
                   3130:   /* Diag(w_x) */
1.292     brouard  3131:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3132:   sumnew=0.;
1.269     brouard  3133:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3134:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3135:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3136:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3137:   }
                   3138:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3139:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3140:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3141:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3142:     }
                   3143:   }else{
                   3144:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3145:       for (j=1;j<=nlstate+ndeath;j++)
                   3146:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3147:     }
                   3148:     /* if(sumnew <0.9){ */
                   3149:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3150:     /* } */
                   3151:   }
                   3152:   k3=0.0;  /* We put the last diagonal to 0 */
                   3153:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3154:       doldm[ii][ii]= k3;
                   3155:   }
                   3156:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3157:   
1.292     brouard  3158:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3159:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3160: 
1.292     brouard  3161:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3162:   /* 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  3163:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3164:     sumnew=0.;
1.222     brouard  3165:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3166:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3167:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3168:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3169:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3170:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3171:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3172:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3173:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3174:        /* }else */
1.268     brouard  3175:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3176:     } /*End ii */
                   3177:   } /* 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 */
                   3178: 
1.292     brouard  3179:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3180:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3181:   /* end bmij */
1.266     brouard  3182:   return ps; /*pointer is unchanged */
1.218     brouard  3183: }
1.217     brouard  3184: /*************** transition probabilities ***************/ 
                   3185: 
1.218     brouard  3186: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3187: {
                   3188:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3189:      computes the probability to be observed in state j being in state i by appying the
                   3190:      model to the ncovmodel covariates (including constant and age).
                   3191:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3192:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3193:      ncth covariate in the global vector x is given by the formula:
                   3194:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3195:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3196:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3197:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3198:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3199:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3200:   */
                   3201:   double s1, lnpijopii;
                   3202:   /*double t34;*/
                   3203:   int i,j, nc, ii, jj;
                   3204: 
1.234     brouard  3205:   for(i=1; i<= nlstate; i++){
                   3206:     for(j=1; j<i;j++){
                   3207:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3208:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3209:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3210:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3211:       }
                   3212:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3213:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3214:     }
                   3215:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3216:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3217:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3218:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3219:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3220:       }
                   3221:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3222:     }
                   3223:   }
                   3224:   
                   3225:   for(i=1; i<= nlstate; i++){
                   3226:     s1=0;
                   3227:     for(j=1; j<i; j++){
                   3228:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3229:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3230:     }
                   3231:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3232:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3233:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3234:     }
                   3235:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3236:     ps[i][i]=1./(s1+1.);
                   3237:     /* Computing other pijs */
                   3238:     for(j=1; j<i; j++)
                   3239:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3240:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3241:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3242:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3243:   } /* end i */
                   3244:   
                   3245:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3246:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3247:       ps[ii][jj]=0;
                   3248:       ps[ii][ii]=1;
                   3249:     }
                   3250:   }
1.296     brouard  3251:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3252:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3253:     s1=0.;
                   3254:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3255:       s1+=ps[ii][jj];
                   3256:     }
                   3257:     for(ii=1; ii<= nlstate; ii++){
                   3258:       ps[ii][jj]=ps[ii][jj]/s1;
                   3259:     }
                   3260:   }
                   3261:   /* Transposition */
                   3262:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3263:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3264:       s1=ps[ii][jj];
                   3265:       ps[ii][jj]=ps[jj][ii];
                   3266:       ps[jj][ii]=s1;
                   3267:     }
                   3268:   }
                   3269:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3270:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3271:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3272:   /*   } */
                   3273:   /*   printf("\n "); */
                   3274:   /* } */
                   3275:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3276:   /*
                   3277:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3278:     goto end;*/
                   3279:   return ps;
1.217     brouard  3280: }
                   3281: 
                   3282: 
1.126     brouard  3283: /**************** Product of 2 matrices ******************/
                   3284: 
1.145     brouard  3285: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3286: {
                   3287:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3288:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3289:   /* in, b, out are matrice of pointers which should have been initialized 
                   3290:      before: only the contents of out is modified. The function returns
                   3291:      a pointer to pointers identical to out */
1.145     brouard  3292:   int i, j, k;
1.126     brouard  3293:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3294:     for(k=ncolol; k<=ncoloh; k++){
                   3295:       out[i][k]=0.;
                   3296:       for(j=ncl; j<=nch; j++)
                   3297:        out[i][k] +=in[i][j]*b[j][k];
                   3298:     }
1.126     brouard  3299:   return out;
                   3300: }
                   3301: 
                   3302: 
                   3303: /************* Higher Matrix Product ***************/
                   3304: 
1.235     brouard  3305: 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  3306: {
1.218     brouard  3307:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3308:      'nhstepm*hstepm*stepm' months (i.e. until
                   3309:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3310:      nhstepm*hstepm matrices. 
                   3311:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3312:      (typically every 2 years instead of every month which is too big 
                   3313:      for the memory).
                   3314:      Model is determined by parameters x and covariates have to be 
                   3315:      included manually here. 
                   3316: 
                   3317:      */
                   3318: 
                   3319:   int i, j, d, h, k;
1.131     brouard  3320:   double **out, cov[NCOVMAX+1];
1.126     brouard  3321:   double **newm;
1.187     brouard  3322:   double agexact;
1.214     brouard  3323:   double agebegin, ageend;
1.126     brouard  3324: 
                   3325:   /* Hstepm could be zero and should return the unit matrix */
                   3326:   for (i=1;i<=nlstate+ndeath;i++)
                   3327:     for (j=1;j<=nlstate+ndeath;j++){
                   3328:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3329:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3330:     }
                   3331:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3332:   for(h=1; h <=nhstepm; h++){
                   3333:     for(d=1; d <=hstepm; d++){
                   3334:       newm=savm;
                   3335:       /* Covariates have to be included here again */
                   3336:       cov[1]=1.;
1.214     brouard  3337:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3338:       cov[2]=agexact;
                   3339:       if(nagesqr==1)
1.227     brouard  3340:        cov[3]= agexact*agexact;
1.235     brouard  3341:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3342:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3343:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3344:        /* 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)); */
                   3345:       }
                   3346:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3347:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3348:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3349:        /* 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]); */
                   3350:       }
                   3351:       for (k=1; k<=cptcovage;k++){
                   3352:        if(Dummy[Tvar[Tage[k]]]){
                   3353:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3354:        } else{
                   3355:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3356:        }
                   3357:        /* 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]); */
                   3358:       }
                   3359:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3360:        /* 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]); */
                   3361:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3362:       }
                   3363:       /* for (k=1; k<=cptcovn;k++)  */
                   3364:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3365:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3366:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3367:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3368:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3369:       
                   3370:       
1.126     brouard  3371:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3372:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3373:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3374:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3375:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3376:       /* if((int)age == 70){ */
                   3377:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3378:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3379:       /*         printf("%d pmmij ",i); */
                   3380:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3381:       /*           printf("%f ",pmmij[i][j]); */
                   3382:       /*         } */
                   3383:       /*         printf(" oldm "); */
                   3384:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3385:       /*           printf("%f ",oldm[i][j]); */
                   3386:       /*         } */
                   3387:       /*         printf("\n"); */
                   3388:       /*       } */
                   3389:       /* } */
1.126     brouard  3390:       savm=oldm;
                   3391:       oldm=newm;
                   3392:     }
                   3393:     for(i=1; i<=nlstate+ndeath; i++)
                   3394:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3395:        po[i][j][h]=newm[i][j];
                   3396:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3397:       }
1.128     brouard  3398:     /*printf("h=%d ",h);*/
1.126     brouard  3399:   } /* end h */
1.267     brouard  3400:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3401:   return po;
                   3402: }
                   3403: 
1.217     brouard  3404: /************* Higher Back Matrix Product ***************/
1.218     brouard  3405: /* 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  3406: 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  3407: {
1.266     brouard  3408:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3409:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3410:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3411:      nhstepm*hstepm matrices.
                   3412:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3413:      (typically every 2 years instead of every month which is too big
1.217     brouard  3414:      for the memory).
1.218     brouard  3415:      Model is determined by parameters x and covariates have to be
1.266     brouard  3416:      included manually here. Then we use a call to bmij(x and cov)
                   3417:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3418:   */
1.217     brouard  3419: 
                   3420:   int i, j, d, h, k;
1.266     brouard  3421:   double **out, cov[NCOVMAX+1], **bmij();
                   3422:   double **newm, ***newmm;
1.217     brouard  3423:   double agexact;
                   3424:   double agebegin, ageend;
1.222     brouard  3425:   double **oldm, **savm;
1.217     brouard  3426: 
1.266     brouard  3427:   newmm=po; /* To be saved */
                   3428:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3429:   /* Hstepm could be zero and should return the unit matrix */
                   3430:   for (i=1;i<=nlstate+ndeath;i++)
                   3431:     for (j=1;j<=nlstate+ndeath;j++){
                   3432:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3433:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3434:     }
                   3435:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3436:   for(h=1; h <=nhstepm; h++){
                   3437:     for(d=1; d <=hstepm; d++){
                   3438:       newm=savm;
                   3439:       /* Covariates have to be included here again */
                   3440:       cov[1]=1.;
1.271     brouard  3441:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3442:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3443:       cov[2]=agexact;
                   3444:       if(nagesqr==1)
1.222     brouard  3445:        cov[3]= agexact*agexact;
1.266     brouard  3446:       for (k=1; k<=cptcovn;k++){
                   3447:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3448:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3449:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3450:         /* 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)); */
                   3451:       }
1.267     brouard  3452:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3453:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3454:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3455:        /* 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]); */
                   3456:       }
                   3457:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3458:        if(Dummy[Tvar[Tage[k]]]){
                   3459:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3460:        } else{
                   3461:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3462:        }
                   3463:        /* 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]); */
                   3464:       }
                   3465:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3466:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3467:       }                        
1.217     brouard  3468:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3469:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3470: 
1.218     brouard  3471:       /* Careful transposed matrix */
1.266     brouard  3472:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3473:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3474:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3475:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3476:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3477:       /* if((int)age == 70){ */
                   3478:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3479:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3480:       /*         printf("%d pmmij ",i); */
                   3481:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3482:       /*           printf("%f ",pmmij[i][j]); */
                   3483:       /*         } */
                   3484:       /*         printf(" oldm "); */
                   3485:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3486:       /*           printf("%f ",oldm[i][j]); */
                   3487:       /*         } */
                   3488:       /*         printf("\n"); */
                   3489:       /*       } */
                   3490:       /* } */
                   3491:       savm=oldm;
                   3492:       oldm=newm;
                   3493:     }
                   3494:     for(i=1; i<=nlstate+ndeath; i++)
                   3495:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3496:        po[i][j][h]=newm[i][j];
1.268     brouard  3497:        /* if(h==nhstepm) */
                   3498:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3499:       }
1.268     brouard  3500:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3501:   } /* end h */
1.268     brouard  3502:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3503:   return po;
                   3504: }
                   3505: 
                   3506: 
1.162     brouard  3507: #ifdef NLOPT
                   3508:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3509:   double fret;
                   3510:   double *xt;
                   3511:   int j;
                   3512:   myfunc_data *d2 = (myfunc_data *) pd;
                   3513: /* xt = (p1-1); */
                   3514:   xt=vector(1,n); 
                   3515:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3516: 
                   3517:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3518:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3519:   printf("Function = %.12lf ",fret);
                   3520:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3521:   printf("\n");
                   3522:  free_vector(xt,1,n);
                   3523:   return fret;
                   3524: }
                   3525: #endif
1.126     brouard  3526: 
                   3527: /*************** log-likelihood *************/
                   3528: double func( double *x)
                   3529: {
1.226     brouard  3530:   int i, ii, j, k, mi, d, kk;
                   3531:   int ioffset=0;
                   3532:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3533:   double **out;
                   3534:   double lli; /* Individual log likelihood */
                   3535:   int s1, s2;
1.228     brouard  3536:   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  3537:   double bbh, survp;
                   3538:   long ipmx;
                   3539:   double agexact;
                   3540:   /*extern weight */
                   3541:   /* We are differentiating ll according to initial status */
                   3542:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3543:   /*for(i=1;i<imx;i++) 
                   3544:     printf(" %d\n",s[4][i]);
                   3545:   */
1.162     brouard  3546: 
1.226     brouard  3547:   ++countcallfunc;
1.162     brouard  3548: 
1.226     brouard  3549:   cov[1]=1.;
1.126     brouard  3550: 
1.226     brouard  3551:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3552:   ioffset=0;
1.226     brouard  3553:   if(mle==1){
                   3554:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3555:       /* Computes the values of the ncovmodel covariates of the model
                   3556:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3557:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3558:         to be observed in j being in i according to the model.
                   3559:       */
1.243     brouard  3560:       ioffset=2+nagesqr ;
1.233     brouard  3561:    /* Fixed */
1.234     brouard  3562:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3563:        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)*/
                   3564:       }
1.226     brouard  3565:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3566:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3567:         has been calculated etc */
                   3568:       /* For an individual i, wav[i] gives the number of effective waves */
                   3569:       /* We compute the contribution to Likelihood of each effective transition
                   3570:         mw[mi][i] is real wave of the mi th effectve wave */
                   3571:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3572:         s2=s[mw[mi+1][i]][i];
                   3573:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3574:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3575:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3576:       */
                   3577:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3578:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3579:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3580:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3581:        }
                   3582:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3583:          for (j=1;j<=nlstate+ndeath;j++){
                   3584:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3585:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3586:          }
                   3587:        for(d=0; d<dh[mi][i]; d++){
                   3588:          newm=savm;
                   3589:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3590:          cov[2]=agexact;
                   3591:          if(nagesqr==1)
                   3592:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3593:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3594:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3595:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3596:          else
                   3597:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3598:          }
                   3599:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3600:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3601:          savm=oldm;
                   3602:          oldm=newm;
                   3603:        } /* end mult */
                   3604:        
                   3605:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3606:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3607:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3608:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3609:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3610:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3611:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3612:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3613:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3614:                                 * -stepm/2 to stepm/2 .
                   3615:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3616:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3617:                                 */
1.234     brouard  3618:        s1=s[mw[mi][i]][i];
                   3619:        s2=s[mw[mi+1][i]][i];
                   3620:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3621:        /* bias bh is positive if real duration
                   3622:         * is higher than the multiple of stepm and negative otherwise.
                   3623:         */
                   3624:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3625:        if( s2 > nlstate){ 
                   3626:          /* i.e. if s2 is a death state and if the date of death is known 
                   3627:             then the contribution to the likelihood is the probability to 
                   3628:             die between last step unit time and current  step unit time, 
                   3629:             which is also equal to probability to die before dh 
                   3630:             minus probability to die before dh-stepm . 
                   3631:             In version up to 0.92 likelihood was computed
                   3632:             as if date of death was unknown. Death was treated as any other
                   3633:             health state: the date of the interview describes the actual state
                   3634:             and not the date of a change in health state. The former idea was
                   3635:             to consider that at each interview the state was recorded
                   3636:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3637:             introduced the exact date of death then we should have modified
                   3638:             the contribution of an exact death to the likelihood. This new
                   3639:             contribution is smaller and very dependent of the step unit
                   3640:             stepm. It is no more the probability to die between last interview
                   3641:             and month of death but the probability to survive from last
                   3642:             interview up to one month before death multiplied by the
                   3643:             probability to die within a month. Thanks to Chris
                   3644:             Jackson for correcting this bug.  Former versions increased
                   3645:             mortality artificially. The bad side is that we add another loop
                   3646:             which slows down the processing. The difference can be up to 10%
                   3647:             lower mortality.
                   3648:          */
                   3649:          /* If, at the beginning of the maximization mostly, the
                   3650:             cumulative probability or probability to be dead is
                   3651:             constant (ie = 1) over time d, the difference is equal to
                   3652:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3653:             s1 at precedent wave, to be dead a month before current
                   3654:             wave is equal to probability, being at state s1 at
                   3655:             precedent wave, to be dead at mont of the current
                   3656:             wave. Then the observed probability (that this person died)
                   3657:             is null according to current estimated parameter. In fact,
                   3658:             it should be very low but not zero otherwise the log go to
                   3659:             infinity.
                   3660:          */
1.183     brouard  3661: /* #ifdef INFINITYORIGINAL */
                   3662: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3663: /* #else */
                   3664: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3665: /*         lli=log(mytinydouble); */
                   3666: /*       else */
                   3667: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3668: /* #endif */
1.226     brouard  3669:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3670:          
1.226     brouard  3671:        } else if  ( s2==-1 ) { /* alive */
                   3672:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3673:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3674:          /*survp += out[s1][j]; */
                   3675:          lli= log(survp);
                   3676:        }
                   3677:        else if  (s2==-4) { 
                   3678:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3679:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3680:          lli= log(survp); 
                   3681:        } 
                   3682:        else if  (s2==-5) { 
                   3683:          for (j=1,survp=0. ; j<=2; j++)  
                   3684:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3685:          lli= log(survp); 
                   3686:        } 
                   3687:        else{
                   3688:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3689:          /*  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 */
                   3690:        } 
                   3691:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3692:        /*if(lli ==000.0)*/
                   3693:        /*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); */
                   3694:        ipmx +=1;
                   3695:        sw += weight[i];
                   3696:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3697:        /* if (lli < log(mytinydouble)){ */
                   3698:        /*   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); */
                   3699:        /*   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]); */
                   3700:        /* } */
                   3701:       } /* end of wave */
                   3702:     } /* end of individual */
                   3703:   }  else if(mle==2){
                   3704:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3705:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3706:       for(mi=1; mi<= wav[i]-1; mi++){
                   3707:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3708:          for (j=1;j<=nlstate+ndeath;j++){
                   3709:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3710:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3711:          }
                   3712:        for(d=0; d<=dh[mi][i]; d++){
                   3713:          newm=savm;
                   3714:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3715:          cov[2]=agexact;
                   3716:          if(nagesqr==1)
                   3717:            cov[3]= agexact*agexact;
                   3718:          for (kk=1; kk<=cptcovage;kk++) {
                   3719:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3720:          }
                   3721:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3722:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3723:          savm=oldm;
                   3724:          oldm=newm;
                   3725:        } /* end mult */
                   3726:       
                   3727:        s1=s[mw[mi][i]][i];
                   3728:        s2=s[mw[mi+1][i]][i];
                   3729:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3730:        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 */
                   3731:        ipmx +=1;
                   3732:        sw += weight[i];
                   3733:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3734:       } /* end of wave */
                   3735:     } /* end of individual */
                   3736:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3737:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3738:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3739:       for(mi=1; mi<= wav[i]-1; mi++){
                   3740:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3741:          for (j=1;j<=nlstate+ndeath;j++){
                   3742:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3743:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3744:          }
                   3745:        for(d=0; d<dh[mi][i]; d++){
                   3746:          newm=savm;
                   3747:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3748:          cov[2]=agexact;
                   3749:          if(nagesqr==1)
                   3750:            cov[3]= agexact*agexact;
                   3751:          for (kk=1; kk<=cptcovage;kk++) {
                   3752:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3753:          }
                   3754:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3755:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3756:          savm=oldm;
                   3757:          oldm=newm;
                   3758:        } /* end mult */
                   3759:       
                   3760:        s1=s[mw[mi][i]][i];
                   3761:        s2=s[mw[mi+1][i]][i];
                   3762:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3763:        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 */
                   3764:        ipmx +=1;
                   3765:        sw += weight[i];
                   3766:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3767:       } /* end of wave */
                   3768:     } /* end of individual */
                   3769:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3770:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3771:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3772:       for(mi=1; mi<= wav[i]-1; mi++){
                   3773:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3774:          for (j=1;j<=nlstate+ndeath;j++){
                   3775:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3776:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3777:          }
                   3778:        for(d=0; d<dh[mi][i]; d++){
                   3779:          newm=savm;
                   3780:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3781:          cov[2]=agexact;
                   3782:          if(nagesqr==1)
                   3783:            cov[3]= agexact*agexact;
                   3784:          for (kk=1; kk<=cptcovage;kk++) {
                   3785:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3786:          }
1.126     brouard  3787:        
1.226     brouard  3788:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3789:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3790:          savm=oldm;
                   3791:          oldm=newm;
                   3792:        } /* end mult */
                   3793:       
                   3794:        s1=s[mw[mi][i]][i];
                   3795:        s2=s[mw[mi+1][i]][i];
                   3796:        if( s2 > nlstate){ 
                   3797:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3798:        } else if  ( s2==-1 ) { /* alive */
                   3799:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3800:            survp += out[s1][j];
                   3801:          lli= log(survp);
                   3802:        }else{
                   3803:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3804:        }
                   3805:        ipmx +=1;
                   3806:        sw += weight[i];
                   3807:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3808: /*     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  3809:       } /* end of wave */
                   3810:     } /* end of individual */
                   3811:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3812:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3813:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3814:       for(mi=1; mi<= wav[i]-1; mi++){
                   3815:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3816:          for (j=1;j<=nlstate+ndeath;j++){
                   3817:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3818:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3819:          }
                   3820:        for(d=0; d<dh[mi][i]; d++){
                   3821:          newm=savm;
                   3822:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3823:          cov[2]=agexact;
                   3824:          if(nagesqr==1)
                   3825:            cov[3]= agexact*agexact;
                   3826:          for (kk=1; kk<=cptcovage;kk++) {
                   3827:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3828:          }
1.126     brouard  3829:        
1.226     brouard  3830:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3831:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3832:          savm=oldm;
                   3833:          oldm=newm;
                   3834:        } /* end mult */
                   3835:       
                   3836:        s1=s[mw[mi][i]][i];
                   3837:        s2=s[mw[mi+1][i]][i];
                   3838:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3839:        ipmx +=1;
                   3840:        sw += weight[i];
                   3841:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3842:        /*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]);*/
                   3843:       } /* end of wave */
                   3844:     } /* end of individual */
                   3845:   } /* End of if */
                   3846:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3847:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3848:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3849:   return -l;
1.126     brouard  3850: }
                   3851: 
                   3852: /*************** log-likelihood *************/
                   3853: double funcone( double *x)
                   3854: {
1.228     brouard  3855:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3856:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3857:   int ioffset=0;
1.131     brouard  3858:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3859:   double **out;
                   3860:   double lli; /* Individual log likelihood */
                   3861:   double llt;
                   3862:   int s1, s2;
1.228     brouard  3863:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3864: 
1.126     brouard  3865:   double bbh, survp;
1.187     brouard  3866:   double agexact;
1.214     brouard  3867:   double agebegin, ageend;
1.126     brouard  3868:   /*extern weight */
                   3869:   /* We are differentiating ll according to initial status */
                   3870:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3871:   /*for(i=1;i<imx;i++) 
                   3872:     printf(" %d\n",s[4][i]);
                   3873:   */
                   3874:   cov[1]=1.;
                   3875: 
                   3876:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3877:   ioffset=0;
                   3878:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3879:     /* ioffset=2+nagesqr+cptcovage; */
                   3880:     ioffset=2+nagesqr;
1.232     brouard  3881:     /* Fixed */
1.224     brouard  3882:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3883:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  3884:     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  3885:       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)*/
                   3886: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3887: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3888: /*    cov[2+6]=covar[2][i]; V2  */
                   3889: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3890: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3891: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3892: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3893: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3894: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3895:     }
1.232     brouard  3896:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3897:     /*   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?)*\/ */
                   3898:     /* } */
1.231     brouard  3899:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3900:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3901:     /* } */
1.225     brouard  3902:     
1.233     brouard  3903: 
                   3904:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3905:     /* Wave varying (but not age varying) */
                   3906:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3907:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3908:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3909:       }
1.232     brouard  3910:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3911:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3912:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3913:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3914:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3915:       /* 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  3916:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3917:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3918:       /*       /\* 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]); *\/ */
                   3919:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3920:       /* } */
1.126     brouard  3921:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3922:        for (j=1;j<=nlstate+ndeath;j++){
                   3923:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3924:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3925:        }
1.214     brouard  3926:       
                   3927:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3928:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3929:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3930:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3931:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3932:          and mw[mi+1][i]. dh depends on stepm.*/
                   3933:        newm=savm;
1.247     brouard  3934:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3935:        cov[2]=agexact;
                   3936:        if(nagesqr==1)
                   3937:          cov[3]= agexact*agexact;
                   3938:        for (kk=1; kk<=cptcovage;kk++) {
                   3939:          if(!FixedV[Tvar[Tage[kk]]])
                   3940:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3941:          else
                   3942:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3943:        }
                   3944:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3945:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3946:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3947:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3948:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3949:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3950:        savm=oldm;
                   3951:        oldm=newm;
1.126     brouard  3952:       } /* end mult */
                   3953:       
                   3954:       s1=s[mw[mi][i]][i];
                   3955:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3956:       /* if(s2==-1){ */
1.268     brouard  3957:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3958:       /*       /\* exit(1); *\/ */
                   3959:       /* } */
1.126     brouard  3960:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3961:       /* bias is positive if real duration
                   3962:        * is higher than the multiple of stepm and negative otherwise.
                   3963:        */
                   3964:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3965:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3966:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3967:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3968:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3969:        lli= log(survp);
1.126     brouard  3970:       }else if (mle==1){
1.242     brouard  3971:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3972:       } else if(mle==2){
1.242     brouard  3973:        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  3974:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3975:        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  3976:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3977:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3978:       } else{  /* mle=0 back to 1 */
1.242     brouard  3979:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3980:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3981:       } /* End of if */
                   3982:       ipmx +=1;
                   3983:       sw += weight[i];
                   3984:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3985:       /*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  3986:       if(globpr){
1.246     brouard  3987:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3988:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3989:                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  3990:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3991:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3992:          llt +=ll[k]*gipmx/gsw;
                   3993:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3994:        }
                   3995:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3996:       }
1.232     brouard  3997:        } /* end of wave */
                   3998: } /* end of individual */
                   3999: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4000: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4001: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4002: if(globpr==0){ /* First time we count the contributions and weights */
                   4003:        gipmx=ipmx;
                   4004:        gsw=sw;
                   4005: }
                   4006: return -l;
1.126     brouard  4007: }
                   4008: 
                   4009: 
                   4010: /*************** function likelione ***********/
1.292     brouard  4011: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4012: {
                   4013:   /* This routine should help understanding what is done with 
                   4014:      the selection of individuals/waves and
                   4015:      to check the exact contribution to the likelihood.
                   4016:      Plotting could be done.
                   4017:    */
                   4018:   int k;
                   4019: 
                   4020:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4021:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4022:     strcat(fileresilk,fileresu);
1.126     brouard  4023:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4024:       printf("Problem with resultfile: %s\n", fileresilk);
                   4025:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4026:     }
1.214     brouard  4027:     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");
                   4028:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4029:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4030:     for(k=1; k<=nlstate; k++) 
                   4031:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4032:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4033:   }
                   4034: 
1.292     brouard  4035:   *fretone=(*func)(p);
1.126     brouard  4036:   if(*globpri !=0){
                   4037:     fclose(ficresilk);
1.205     brouard  4038:     if (mle ==0)
                   4039:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4040:     else if(mle >=1)
                   4041:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4042:     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  4043:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4044:       
                   4045:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4046:       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  4047: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4048:     }
1.207     brouard  4049:     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  4050: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4051:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4052: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4053:     fflush(fichtm);
1.205     brouard  4054:   }
1.126     brouard  4055:   return;
                   4056: }
                   4057: 
                   4058: 
                   4059: /*********** Maximum Likelihood Estimation ***************/
                   4060: 
                   4061: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4062: {
1.165     brouard  4063:   int i,j, iter=0;
1.126     brouard  4064:   double **xi;
                   4065:   double fret;
                   4066:   double fretone; /* Only one call to likelihood */
                   4067:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4068: 
                   4069: #ifdef NLOPT
                   4070:   int creturn;
                   4071:   nlopt_opt opt;
                   4072:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4073:   double *lb;
                   4074:   double minf; /* the minimum objective value, upon return */
                   4075:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4076:   myfunc_data dinst, *d = &dinst;
                   4077: #endif
                   4078: 
                   4079: 
1.126     brouard  4080:   xi=matrix(1,npar,1,npar);
                   4081:   for (i=1;i<=npar;i++)
                   4082:     for (j=1;j<=npar;j++)
                   4083:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4084:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4085:   strcpy(filerespow,"POW_"); 
1.126     brouard  4086:   strcat(filerespow,fileres);
                   4087:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4088:     printf("Problem with resultfile: %s\n", filerespow);
                   4089:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4090:   }
                   4091:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4092:   for (i=1;i<=nlstate;i++)
                   4093:     for(j=1;j<=nlstate+ndeath;j++)
                   4094:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4095:   fprintf(ficrespow,"\n");
1.162     brouard  4096: #ifdef POWELL
1.126     brouard  4097:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4098: #endif
1.126     brouard  4099: 
1.162     brouard  4100: #ifdef NLOPT
                   4101: #ifdef NEWUOA
                   4102:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4103: #else
                   4104:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4105: #endif
                   4106:   lb=vector(0,npar-1);
                   4107:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4108:   nlopt_set_lower_bounds(opt, lb);
                   4109:   nlopt_set_initial_step1(opt, 0.1);
                   4110:   
                   4111:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4112:   d->function = func;
                   4113:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4114:   nlopt_set_min_objective(opt, myfunc, d);
                   4115:   nlopt_set_xtol_rel(opt, ftol);
                   4116:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4117:     printf("nlopt failed! %d\n",creturn); 
                   4118:   }
                   4119:   else {
                   4120:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4121:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4122:     iter=1; /* not equal */
                   4123:   }
                   4124:   nlopt_destroy(opt);
                   4125: #endif
1.126     brouard  4126:   free_matrix(xi,1,npar,1,npar);
                   4127:   fclose(ficrespow);
1.203     brouard  4128:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4129:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4130:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4131: 
                   4132: }
                   4133: 
                   4134: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4135: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4136: {
                   4137:   double  **a,**y,*x,pd;
1.203     brouard  4138:   /* double **hess; */
1.164     brouard  4139:   int i, j;
1.126     brouard  4140:   int *indx;
                   4141: 
                   4142:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4143:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4144:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4145:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4146:   double gompertz(double p[]);
1.203     brouard  4147:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4148: 
                   4149:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4150:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4151:   for (i=1;i<=npar;i++){
1.203     brouard  4152:     printf("%d-",i);fflush(stdout);
                   4153:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4154:    
                   4155:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4156:     
                   4157:     /*  printf(" %f ",p[i]);
                   4158:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4159:   }
                   4160:   
                   4161:   for (i=1;i<=npar;i++) {
                   4162:     for (j=1;j<=npar;j++)  {
                   4163:       if (j>i) { 
1.203     brouard  4164:        printf(".%d-%d",i,j);fflush(stdout);
                   4165:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4166:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4167:        
                   4168:        hess[j][i]=hess[i][j];    
                   4169:        /*printf(" %lf ",hess[i][j]);*/
                   4170:       }
                   4171:     }
                   4172:   }
                   4173:   printf("\n");
                   4174:   fprintf(ficlog,"\n");
                   4175: 
                   4176:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4177:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4178:   
                   4179:   a=matrix(1,npar,1,npar);
                   4180:   y=matrix(1,npar,1,npar);
                   4181:   x=vector(1,npar);
                   4182:   indx=ivector(1,npar);
                   4183:   for (i=1;i<=npar;i++)
                   4184:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4185:   ludcmp(a,npar,indx,&pd);
                   4186: 
                   4187:   for (j=1;j<=npar;j++) {
                   4188:     for (i=1;i<=npar;i++) x[i]=0;
                   4189:     x[j]=1;
                   4190:     lubksb(a,npar,indx,x);
                   4191:     for (i=1;i<=npar;i++){ 
                   4192:       matcov[i][j]=x[i];
                   4193:     }
                   4194:   }
                   4195: 
                   4196:   printf("\n#Hessian matrix#\n");
                   4197:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4198:   for (i=1;i<=npar;i++) { 
                   4199:     for (j=1;j<=npar;j++) { 
1.203     brouard  4200:       printf("%.6e ",hess[i][j]);
                   4201:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4202:     }
                   4203:     printf("\n");
                   4204:     fprintf(ficlog,"\n");
                   4205:   }
                   4206: 
1.203     brouard  4207:   /* printf("\n#Covariance matrix#\n"); */
                   4208:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4209:   /* for (i=1;i<=npar;i++) {  */
                   4210:   /*   for (j=1;j<=npar;j++) {  */
                   4211:   /*     printf("%.6e ",matcov[i][j]); */
                   4212:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4213:   /*   } */
                   4214:   /*   printf("\n"); */
                   4215:   /*   fprintf(ficlog,"\n"); */
                   4216:   /* } */
                   4217: 
1.126     brouard  4218:   /* Recompute Inverse */
1.203     brouard  4219:   /* for (i=1;i<=npar;i++) */
                   4220:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4221:   /* ludcmp(a,npar,indx,&pd); */
                   4222: 
                   4223:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4224: 
                   4225:   /* for (j=1;j<=npar;j++) { */
                   4226:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4227:   /*   x[j]=1; */
                   4228:   /*   lubksb(a,npar,indx,x); */
                   4229:   /*   for (i=1;i<=npar;i++){  */
                   4230:   /*     y[i][j]=x[i]; */
                   4231:   /*     printf("%.3e ",y[i][j]); */
                   4232:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4233:   /*   } */
                   4234:   /*   printf("\n"); */
                   4235:   /*   fprintf(ficlog,"\n"); */
                   4236:   /* } */
                   4237: 
                   4238:   /* Verifying the inverse matrix */
                   4239: #ifdef DEBUGHESS
                   4240:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4241: 
1.203     brouard  4242:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4243:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4244: 
                   4245:   for (j=1;j<=npar;j++) {
                   4246:     for (i=1;i<=npar;i++){ 
1.203     brouard  4247:       printf("%.2f ",y[i][j]);
                   4248:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4249:     }
                   4250:     printf("\n");
                   4251:     fprintf(ficlog,"\n");
                   4252:   }
1.203     brouard  4253: #endif
1.126     brouard  4254: 
                   4255:   free_matrix(a,1,npar,1,npar);
                   4256:   free_matrix(y,1,npar,1,npar);
                   4257:   free_vector(x,1,npar);
                   4258:   free_ivector(indx,1,npar);
1.203     brouard  4259:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4260: 
                   4261: 
                   4262: }
                   4263: 
                   4264: /*************** hessian matrix ****************/
                   4265: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4266: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4267:   int i;
                   4268:   int l=1, lmax=20;
1.203     brouard  4269:   double k1,k2, res, fx;
1.132     brouard  4270:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4271:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4272:   int k=0,kmax=10;
                   4273:   double l1;
                   4274: 
                   4275:   fx=func(x);
                   4276:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4277:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4278:     l1=pow(10,l);
                   4279:     delts=delt;
                   4280:     for(k=1 ; k <kmax; k=k+1){
                   4281:       delt = delta*(l1*k);
                   4282:       p2[theta]=x[theta] +delt;
1.145     brouard  4283:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4284:       p2[theta]=x[theta]-delt;
                   4285:       k2=func(p2)-fx;
                   4286:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4287:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4288:       
1.203     brouard  4289: #ifdef DEBUGHESSII
1.126     brouard  4290:       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);
                   4291:       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);
                   4292: #endif
                   4293:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4294:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4295:        k=kmax;
                   4296:       }
                   4297:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4298:        k=kmax; l=lmax*10;
1.126     brouard  4299:       }
                   4300:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4301:        delts=delt;
                   4302:       }
1.203     brouard  4303:     } /* End loop k */
1.126     brouard  4304:   }
                   4305:   delti[theta]=delts;
                   4306:   return res; 
                   4307:   
                   4308: }
                   4309: 
1.203     brouard  4310: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4311: {
                   4312:   int i;
1.164     brouard  4313:   int l=1, lmax=20;
1.126     brouard  4314:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4315:   double p2[MAXPARM+1];
1.203     brouard  4316:   int k, kmax=1;
                   4317:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4318: 
                   4319:   int firstime=0;
1.203     brouard  4320:   
1.126     brouard  4321:   fx=func(x);
1.203     brouard  4322:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4323:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4324:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4325:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4326:     k1=func(p2)-fx;
                   4327:   
1.203     brouard  4328:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4329:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4330:     k2=func(p2)-fx;
                   4331:   
1.203     brouard  4332:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4333:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4334:     k3=func(p2)-fx;
                   4335:   
1.203     brouard  4336:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4337:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4338:     k4=func(p2)-fx;
1.203     brouard  4339:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4340:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4341:       firstime=1;
1.203     brouard  4342:       kmax=kmax+10;
1.208     brouard  4343:     }
                   4344:     if(kmax >=10 || firstime ==1){
1.246     brouard  4345:       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);
                   4346:       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  4347:       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);
                   4348:       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);
                   4349:     }
                   4350: #ifdef DEBUGHESSIJ
                   4351:     v1=hess[thetai][thetai];
                   4352:     v2=hess[thetaj][thetaj];
                   4353:     cv12=res;
                   4354:     /* Computing eigen value of Hessian matrix */
                   4355:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4356:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4357:     if ((lc2 <0) || (lc1 <0) ){
                   4358:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4359:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4360:       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);
                   4361:       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);
                   4362:     }
1.126     brouard  4363: #endif
                   4364:   }
                   4365:   return res;
                   4366: }
                   4367: 
1.203     brouard  4368:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4369: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4370: /* { */
                   4371: /*   int i; */
                   4372: /*   int l=1, lmax=20; */
                   4373: /*   double k1,k2,k3,k4,res,fx; */
                   4374: /*   double p2[MAXPARM+1]; */
                   4375: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4376: /*   int k=0,kmax=10; */
                   4377: /*   double l1; */
                   4378:   
                   4379: /*   fx=func(x); */
                   4380: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4381: /*     l1=pow(10,l); */
                   4382: /*     delts=delt; */
                   4383: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4384: /*       delt = delti*(l1*k); */
                   4385: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4386: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4387: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4388: /*       k1=func(p2)-fx; */
                   4389:       
                   4390: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4391: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4392: /*       k2=func(p2)-fx; */
                   4393:       
                   4394: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4395: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4396: /*       k3=func(p2)-fx; */
                   4397:       
                   4398: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4399: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4400: /*       k4=func(p2)-fx; */
                   4401: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4402: /* #ifdef DEBUGHESSIJ */
                   4403: /*       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); */
                   4404: /*       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); */
                   4405: /* #endif */
                   4406: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4407: /*     k=kmax; */
                   4408: /*       } */
                   4409: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4410: /*     k=kmax; l=lmax*10; */
                   4411: /*       } */
                   4412: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4413: /*     delts=delt; */
                   4414: /*       } */
                   4415: /*     } /\* End loop k *\/ */
                   4416: /*   } */
                   4417: /*   delti[theta]=delts; */
                   4418: /*   return res;  */
                   4419: /* } */
                   4420: 
                   4421: 
1.126     brouard  4422: /************** Inverse of matrix **************/
                   4423: void ludcmp(double **a, int n, int *indx, double *d) 
                   4424: { 
                   4425:   int i,imax,j,k; 
                   4426:   double big,dum,sum,temp; 
                   4427:   double *vv; 
                   4428:  
                   4429:   vv=vector(1,n); 
                   4430:   *d=1.0; 
                   4431:   for (i=1;i<=n;i++) { 
                   4432:     big=0.0; 
                   4433:     for (j=1;j<=n;j++) 
                   4434:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4435:     if (big == 0.0){
                   4436:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4437:       for (j=1;j<=n;j++) {
                   4438:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4439:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4440:       }
                   4441:       fflush(ficlog);
                   4442:       fclose(ficlog);
                   4443:       nrerror("Singular matrix in routine ludcmp"); 
                   4444:     }
1.126     brouard  4445:     vv[i]=1.0/big; 
                   4446:   } 
                   4447:   for (j=1;j<=n;j++) { 
                   4448:     for (i=1;i<j;i++) { 
                   4449:       sum=a[i][j]; 
                   4450:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4451:       a[i][j]=sum; 
                   4452:     } 
                   4453:     big=0.0; 
                   4454:     for (i=j;i<=n;i++) { 
                   4455:       sum=a[i][j]; 
                   4456:       for (k=1;k<j;k++) 
                   4457:        sum -= a[i][k]*a[k][j]; 
                   4458:       a[i][j]=sum; 
                   4459:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4460:        big=dum; 
                   4461:        imax=i; 
                   4462:       } 
                   4463:     } 
                   4464:     if (j != imax) { 
                   4465:       for (k=1;k<=n;k++) { 
                   4466:        dum=a[imax][k]; 
                   4467:        a[imax][k]=a[j][k]; 
                   4468:        a[j][k]=dum; 
                   4469:       } 
                   4470:       *d = -(*d); 
                   4471:       vv[imax]=vv[j]; 
                   4472:     } 
                   4473:     indx[j]=imax; 
                   4474:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4475:     if (j != n) { 
                   4476:       dum=1.0/(a[j][j]); 
                   4477:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4478:     } 
                   4479:   } 
                   4480:   free_vector(vv,1,n);  /* Doesn't work */
                   4481: ;
                   4482: } 
                   4483: 
                   4484: void lubksb(double **a, int n, int *indx, double b[]) 
                   4485: { 
                   4486:   int i,ii=0,ip,j; 
                   4487:   double sum; 
                   4488:  
                   4489:   for (i=1;i<=n;i++) { 
                   4490:     ip=indx[i]; 
                   4491:     sum=b[ip]; 
                   4492:     b[ip]=b[i]; 
                   4493:     if (ii) 
                   4494:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4495:     else if (sum) ii=i; 
                   4496:     b[i]=sum; 
                   4497:   } 
                   4498:   for (i=n;i>=1;i--) { 
                   4499:     sum=b[i]; 
                   4500:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4501:     b[i]=sum/a[i][i]; 
                   4502:   } 
                   4503: } 
                   4504: 
                   4505: void pstamp(FILE *fichier)
                   4506: {
1.196     brouard  4507:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4508: }
                   4509: 
1.297     brouard  4510: void date2dmy(double date,double *day, double *month, double *year){
                   4511:   double yp=0., yp1=0., yp2=0.;
                   4512:   
                   4513:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4514:                        fractional in yp1 */
                   4515:   *year=yp;
                   4516:   yp2=modf((yp1*12),&yp);
                   4517:   *month=yp;
                   4518:   yp1=modf((yp2*30.5),&yp);
                   4519:   *day=yp;
                   4520:   if(*day==0) *day=1;
                   4521:   if(*month==0) *month=1;
                   4522: }
                   4523: 
1.253     brouard  4524: 
                   4525: 
1.126     brouard  4526: /************ Frequencies ********************/
1.251     brouard  4527: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4528:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4529:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4530: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4531:   
1.265     brouard  4532:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4533:   int iind=0, iage=0;
                   4534:   int mi; /* Effective wave */
                   4535:   int first;
                   4536:   double ***freq; /* Frequencies */
1.268     brouard  4537:   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 */
                   4538:   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  4539:   double *meanq, *stdq, *idq;
1.226     brouard  4540:   double **meanqt;
                   4541:   double *pp, **prop, *posprop, *pospropt;
                   4542:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4543:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4544:   double agebegin, ageend;
                   4545:     
                   4546:   pp=vector(1,nlstate);
1.251     brouard  4547:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4548:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4549:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4550:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4551:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4552:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4553:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4554:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4555:   strcpy(fileresp,"P_");
                   4556:   strcat(fileresp,fileresu);
                   4557:   /*strcat(fileresphtm,fileresu);*/
                   4558:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4559:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4560:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4561:     exit(0);
                   4562:   }
1.240     brouard  4563:   
1.226     brouard  4564:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4565:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4566:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4567:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4568:     fflush(ficlog);
                   4569:     exit(70); 
                   4570:   }
                   4571:   else{
                   4572:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4573: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4574: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4575:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4576:   }
1.237     brouard  4577:   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  4578:   
1.226     brouard  4579:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4580:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4581:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4582:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4583:     fflush(ficlog);
                   4584:     exit(70); 
1.240     brouard  4585:   } else{
1.226     brouard  4586:     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  4587: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4588: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4589:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4590:   }
1.240     brouard  4591:   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);
                   4592:   
1.253     brouard  4593:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4594:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4595:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4596:   j1=0;
1.126     brouard  4597:   
1.227     brouard  4598:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4599:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4600:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4601:   
                   4602:   
1.226     brouard  4603:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4604:      reference=low_education V1=0,V2=0
                   4605:      med_educ                V1=1 V2=0, 
                   4606:      high_educ               V1=0 V2=1
                   4607:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4608:   */
1.249     brouard  4609:   dateintsum=0;
                   4610:   k2cpt=0;
                   4611: 
1.253     brouard  4612:   if(cptcoveff == 0 )
1.265     brouard  4613:     nl=1;  /* Constant and age model only */
1.253     brouard  4614:   else
                   4615:     nl=2;
1.265     brouard  4616: 
                   4617:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4618:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4619:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4620:    *     freq[s1][s2][iage] =0.
                   4621:    *     Loop on iind
                   4622:    *       ++freq[s1][s2][iage] weighted
                   4623:    *     end iind
                   4624:    *     if covariate and j!0
                   4625:    *       headers Variable on one line
                   4626:    *     endif cov j!=0
                   4627:    *     header of frequency table by age
                   4628:    *     Loop on age
                   4629:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4630:    *       pos+=freq[s1][s2][iage] weighted
                   4631:    *       Loop on s1 initial state
                   4632:    *         fprintf(ficresp
                   4633:    *       end s1
                   4634:    *     end age
                   4635:    *     if j!=0 computes starting values
                   4636:    *     end compute starting values
                   4637:    *   end j1
                   4638:    * end nl 
                   4639:    */
1.253     brouard  4640:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4641:     if(nj==1)
                   4642:       j=0;  /* First pass for the constant */
1.265     brouard  4643:     else{
1.253     brouard  4644:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4645:     }
1.251     brouard  4646:     first=1;
1.265     brouard  4647:     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  4648:       posproptt=0.;
                   4649:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4650:        scanf("%d", i);*/
                   4651:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4652:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4653:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4654:            freq[i][s2][m]=0;
1.251     brouard  4655:       
                   4656:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4657:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4658:          prop[i][m]=0;
                   4659:        posprop[i]=0;
                   4660:        pospropt[i]=0;
                   4661:       }
1.283     brouard  4662:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4663:         idq[z1]=0.;
                   4664:         meanq[z1]=0.;
                   4665:         stdq[z1]=0.;
1.283     brouard  4666:       }
                   4667:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4668:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4669:       /*         meanqt[m][z1]=0.; */
                   4670:       /*       } */
                   4671:       /* }       */
1.251     brouard  4672:       /* dateintsum=0; */
                   4673:       /* k2cpt=0; */
                   4674:       
1.265     brouard  4675:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4676:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4677:        bool=1;
                   4678:        if(j !=0){
                   4679:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4680:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4681:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4682:                /* if(Tvaraff[z1] ==-20){ */
                   4683:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4684:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4685:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4686:                /* }else  */
                   4687:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4688:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4689:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4690:                  /* 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", 
                   4691:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4692:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4693:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4694:                } /* Onlyf fixed */
                   4695:              } /* end z1 */
                   4696:            } /* cptcovn > 0 */
                   4697:          } /* end any */
                   4698:        }/* end j==0 */
1.265     brouard  4699:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4700:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4701:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4702:            m=mw[mi][iind];
                   4703:            if(j!=0){
                   4704:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4705:                for (z1=1; z1<=cptcoveff; z1++) {
                   4706:                  if( Fixed[Tmodelind[z1]]==1){
                   4707:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4708:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4709:                                                                                      value is -1, we don't select. It differs from the 
                   4710:                                                                                      constant and age model which counts them. */
                   4711:                      bool=0; /* not selected */
                   4712:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4713:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4714:                      bool=0;
                   4715:                    }
                   4716:                  }
                   4717:                }
                   4718:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4719:            } /* end j==0 */
                   4720:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4721:            if(bool==1){ /*Selected */
1.251     brouard  4722:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4723:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4724:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4725:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4726:              if(m >=firstpass && m <=lastpass){
                   4727:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4728:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4729:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4730:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4731:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4732:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4733:                if (m<lastpass) {
                   4734:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4735:                  /*   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]); */
                   4736:                  if(s[m][iind]==-1)
                   4737:                    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.));
                   4738:                  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  4739:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   4740:                    if(!isnan(covar[ncovcol+z1][iind])){
                   4741:                        idq[z1]=idq[z1]+weight[iind];
                   4742:                        meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4743:                        /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   4744:                        stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4745:                    }
1.284     brouard  4746:                  }
1.251     brouard  4747:                  /* if((int)agev[m][iind] == 55) */
                   4748:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4749:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4750:                  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  4751:                }
1.251     brouard  4752:              } /* end if between passes */  
                   4753:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4754:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4755:                k2cpt++;
                   4756:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4757:              }
1.251     brouard  4758:            }else{
                   4759:              bool=1;
                   4760:            }/* end bool 2 */
                   4761:          } /* end m */
1.284     brouard  4762:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4763:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4764:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4765:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4766:          /* } */
1.251     brouard  4767:        } /* end bool */
                   4768:       } /* end iind = 1 to imx */
                   4769:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4770:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4771:       
                   4772:       
                   4773:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4774:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4775:         pstamp(ficresp);
1.251     brouard  4776:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4777:         pstamp(ficresp);
1.251     brouard  4778:        printf( "\n#********** Variable "); 
                   4779:        fprintf(ficresp, "\n#********** Variable "); 
                   4780:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4781:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4782:        fprintf(ficlog, "\n#********** Variable "); 
                   4783:        for (z1=1; z1<=cptcoveff; z1++){
                   4784:          if(!FixedV[Tvaraff[z1]]){
                   4785:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4786:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4787:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4788:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4789:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4790:          }else{
1.251     brouard  4791:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4792:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4793:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4794:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4795:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4796:          }
                   4797:        }
                   4798:        printf( "**********\n#");
                   4799:        fprintf(ficresp, "**********\n#");
                   4800:        fprintf(ficresphtm, "**********</h3>\n");
                   4801:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4802:        fprintf(ficlog, "**********\n");
                   4803:       }
1.284     brouard  4804:       /*
                   4805:        Printing means of quantitative variables if any
                   4806:       */
                   4807:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  4808:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  4809:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  4810:        if(weightopt==1){
                   4811:          printf(" Weighted mean and standard deviation of");
                   4812:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4813:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4814:        }
1.311     brouard  4815:        /* mu = \frac{w x}{\sum w}
                   4816:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   4817:        */
                   4818:        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]));
                   4819:        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]));
                   4820:        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  4821:       }
                   4822:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4823:       /*       for(m=1;m<=lastpass;m++){ */
                   4824:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4825:       /*   } */
                   4826:       /* } */
1.283     brouard  4827: 
1.251     brouard  4828:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4829:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4830:         fprintf(ficresp, " Age");
                   4831:       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  4832:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4833:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4834:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4835:       }
1.265     brouard  4836:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4837:       fprintf(ficresphtm, "\n");
                   4838:       
                   4839:       /* Header of frequency table by age */
                   4840:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4841:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4842:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4843:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4844:          if(s2!=0 && m!=0)
                   4845:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4846:        }
1.226     brouard  4847:       }
1.251     brouard  4848:       fprintf(ficresphtmfr, "\n");
                   4849:     
                   4850:       /* For each age */
                   4851:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4852:        fprintf(ficresphtm,"<tr>");
                   4853:        if(iage==iagemax+1){
                   4854:          fprintf(ficlog,"1");
                   4855:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4856:        }else if(iage==iagemax+2){
                   4857:          fprintf(ficlog,"0");
                   4858:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4859:        }else if(iage==iagemax+3){
                   4860:          fprintf(ficlog,"Total");
                   4861:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4862:        }else{
1.240     brouard  4863:          if(first==1){
1.251     brouard  4864:            first=0;
                   4865:            printf("See log file for details...\n");
                   4866:          }
                   4867:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4868:          fprintf(ficlog,"Age %d", iage);
                   4869:        }
1.265     brouard  4870:        for(s1=1; s1 <=nlstate ; s1++){
                   4871:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4872:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4873:        }
1.265     brouard  4874:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4875:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4876:            pos += freq[s1][m][iage];
                   4877:          if(pp[s1]>=1.e-10){
1.251     brouard  4878:            if(first==1){
1.265     brouard  4879:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4880:            }
1.265     brouard  4881:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4882:          }else{
                   4883:            if(first==1)
1.265     brouard  4884:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4885:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4886:          }
                   4887:        }
                   4888:       
1.265     brouard  4889:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4890:          /* posprop[s1]=0; */
                   4891:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4892:            pp[s1] += freq[s1][m][iage];
                   4893:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4894:       
                   4895:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4896:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4897:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4898:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4899:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4900:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4901:        }
                   4902:        
                   4903:        /* Writing ficresp */
                   4904:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4905:           if( iage <= iagemax){
                   4906:            fprintf(ficresp," %d",iage);
                   4907:           }
                   4908:         }else if( nj==2){
                   4909:           if( iage <= iagemax){
                   4910:            fprintf(ficresp," %d",iage);
                   4911:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4912:           }
1.240     brouard  4913:        }
1.265     brouard  4914:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4915:          if(pos>=1.e-5){
1.251     brouard  4916:            if(first==1)
1.265     brouard  4917:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4918:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4919:          }else{
                   4920:            if(first==1)
1.265     brouard  4921:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4922:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4923:          }
                   4924:          if( iage <= iagemax){
                   4925:            if(pos>=1.e-5){
1.265     brouard  4926:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4927:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4928:               }else if( nj==2){
                   4929:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4930:               }
                   4931:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4932:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4933:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4934:            } else{
                   4935:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4936:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4937:            }
1.240     brouard  4938:          }
1.265     brouard  4939:          pospropt[s1] +=posprop[s1];
                   4940:        } /* end loop s1 */
1.251     brouard  4941:        /* pospropt=0.; */
1.265     brouard  4942:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4943:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4944:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4945:              if(first==1){
1.265     brouard  4946:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4947:              }
1.265     brouard  4948:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4949:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4950:            }
1.265     brouard  4951:            if(s1!=0 && m!=0)
                   4952:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4953:          }
1.265     brouard  4954:        } /* end loop s1 */
1.251     brouard  4955:        posproptt=0.; 
1.265     brouard  4956:        for(s1=1; s1 <=nlstate; s1++){
                   4957:          posproptt += pospropt[s1];
1.251     brouard  4958:        }
                   4959:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4960:        fprintf(ficresphtm,"</tr>\n");
                   4961:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4962:          if(iage <= iagemax)
                   4963:            fprintf(ficresp,"\n");
1.240     brouard  4964:        }
1.251     brouard  4965:        if(first==1)
                   4966:          printf("Others in log...\n");
                   4967:        fprintf(ficlog,"\n");
                   4968:       } /* end loop age iage */
1.265     brouard  4969:       
1.251     brouard  4970:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4971:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4972:        if(posproptt < 1.e-5){
1.265     brouard  4973:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4974:        }else{
1.265     brouard  4975:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4976:        }
1.226     brouard  4977:       }
1.251     brouard  4978:       fprintf(ficresphtm,"</tr>\n");
                   4979:       fprintf(ficresphtm,"</table>\n");
                   4980:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4981:       if(posproptt < 1.e-5){
1.251     brouard  4982:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4983:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4984:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4985:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4986:        invalidvarcomb[j1]=1;
1.226     brouard  4987:       }else{
1.251     brouard  4988:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4989:        invalidvarcomb[j1]=0;
1.226     brouard  4990:       }
1.251     brouard  4991:       fprintf(ficresphtmfr,"</table>\n");
                   4992:       fprintf(ficlog,"\n");
                   4993:       if(j!=0){
                   4994:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4995:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4996:          for(k=1; k <=(nlstate+ndeath); k++){
                   4997:            if (k != i) {
1.265     brouard  4998:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4999:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5000:                  if(j1==1){ /* All dummy covariates to zero */
                   5001:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5002:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5003:                    printf("%d%d ",i,k);
                   5004:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5005:                    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]));
                   5006:                    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]));
                   5007:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5008:                  }
1.253     brouard  5009:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5010:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5011:                    x[iage]= (double)iage;
                   5012:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5013:                    /* 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  5014:                  }
1.268     brouard  5015:                  /* Some are not finite, but linreg will ignore these ages */
                   5016:                  no=0;
1.253     brouard  5017:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5018:                  pstart[s1]=b;
                   5019:                  pstart[s1-1]=a;
1.252     brouard  5020:                }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 */ 
                   5021:                  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]);
                   5022:                  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  5023:                  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  5024:                  printf("%d%d ",i,k);
                   5025:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5026:                  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  5027:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5028:                  ;
                   5029:                }
                   5030:                /* printf("%12.7f )", param[i][jj][k]); */
                   5031:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5032:                s1++; 
1.251     brouard  5033:              } /* end jj */
                   5034:            } /* end k!= i */
                   5035:          } /* end k */
1.265     brouard  5036:        } /* end i, s1 */
1.251     brouard  5037:       } /* end j !=0 */
                   5038:     } /* end selected combination of covariate j1 */
                   5039:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5040:       printf("#Freqsummary: Starting values for the constants:\n");
                   5041:       fprintf(ficlog,"\n");
1.265     brouard  5042:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5043:        for(k=1; k <=(nlstate+ndeath); k++){
                   5044:          if (k != i) {
                   5045:            printf("%d%d ",i,k);
                   5046:            fprintf(ficlog,"%d%d ",i,k);
                   5047:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5048:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5049:              if(jj==1){ /* Age has to be done */
1.265     brouard  5050:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5051:                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]));
                   5052:                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  5053:              }
                   5054:              /* printf("%12.7f )", param[i][jj][k]); */
                   5055:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5056:              s1++; 
1.250     brouard  5057:            }
1.251     brouard  5058:            printf("\n");
                   5059:            fprintf(ficlog,"\n");
1.250     brouard  5060:          }
                   5061:        }
1.284     brouard  5062:       } /* end of state i */
1.251     brouard  5063:       printf("#Freqsummary\n");
                   5064:       fprintf(ficlog,"\n");
1.265     brouard  5065:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5066:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5067:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5068:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5069:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5070:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5071:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5072:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5073:          /* } */
                   5074:        }
1.265     brouard  5075:       } /* end loop s1 */
1.251     brouard  5076:       
                   5077:       printf("\n");
                   5078:       fprintf(ficlog,"\n");
                   5079:     } /* end j=0 */
1.249     brouard  5080:   } /* end j */
1.252     brouard  5081: 
1.253     brouard  5082:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5083:     for(i=1, jk=1; i <=nlstate; i++){
                   5084:       for(j=1; j <=nlstate+ndeath; j++){
                   5085:        if(j!=i){
                   5086:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5087:          printf("%1d%1d",i,j);
                   5088:          fprintf(ficparo,"%1d%1d",i,j);
                   5089:          for(k=1; k<=ncovmodel;k++){
                   5090:            /*    printf(" %lf",param[i][j][k]); */
                   5091:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5092:            p[jk]=pstart[jk];
                   5093:            printf(" %f ",pstart[jk]);
                   5094:            fprintf(ficparo," %f ",pstart[jk]);
                   5095:            jk++;
                   5096:          }
                   5097:          printf("\n");
                   5098:          fprintf(ficparo,"\n");
                   5099:        }
                   5100:       }
                   5101:     }
                   5102:   } /* end mle=-2 */
1.226     brouard  5103:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5104:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5105:   
1.226     brouard  5106:   fclose(ficresp);
                   5107:   fclose(ficresphtm);
                   5108:   fclose(ficresphtmfr);
1.283     brouard  5109:   free_vector(idq,1,nqfveff);
1.226     brouard  5110:   free_vector(meanq,1,nqfveff);
1.284     brouard  5111:   free_vector(stdq,1,nqfveff);
1.226     brouard  5112:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5113:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5114:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5115:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5116:   free_vector(pospropt,1,nlstate);
                   5117:   free_vector(posprop,1,nlstate);
1.251     brouard  5118:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5119:   free_vector(pp,1,nlstate);
                   5120:   /* End of freqsummary */
                   5121: }
1.126     brouard  5122: 
1.268     brouard  5123: /* Simple linear regression */
                   5124: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5125: 
                   5126:   /* y=a+bx regression */
                   5127:   double   sumx = 0.0;                        /* sum of x                      */
                   5128:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5129:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5130:   double   sumy = 0.0;                        /* sum of y                      */
                   5131:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5132:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5133:   double yhat;
                   5134:   
                   5135:   double denom=0;
                   5136:   int i;
                   5137:   int ne=*no;
                   5138:   
                   5139:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5140:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5141:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5142:       continue;
                   5143:     }
                   5144:     ne=ne+1;
                   5145:     sumx  += x[i];       
                   5146:     sumx2 += x[i]*x[i];  
                   5147:     sumxy += x[i] * y[i];
                   5148:     sumy  += y[i];      
                   5149:     sumy2 += y[i]*y[i]; 
                   5150:     denom = (ne * sumx2 - sumx*sumx);
                   5151:     /* 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); */
                   5152:   } 
                   5153:   
                   5154:   denom = (ne * sumx2 - sumx*sumx);
                   5155:   if (denom == 0) {
                   5156:     // vertical, slope m is infinity
                   5157:     *b = INFINITY;
                   5158:     *a = 0;
                   5159:     if (r) *r = 0;
                   5160:     return 1;
                   5161:   }
                   5162:   
                   5163:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5164:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5165:   if (r!=NULL) {
                   5166:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5167:       sqrt((sumx2 - sumx*sumx/ne) *
                   5168:           (sumy2 - sumy*sumy/ne));
                   5169:   }
                   5170:   *no=ne;
                   5171:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5172:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5173:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5174:       continue;
                   5175:     }
                   5176:     ne=ne+1;
                   5177:     yhat = y[i] - *a -*b* x[i];
                   5178:     sume2  += yhat * yhat ;       
                   5179:     
                   5180:     denom = (ne * sumx2 - sumx*sumx);
                   5181:     /* 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); */
                   5182:   } 
                   5183:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5184:   *sa= *sb * sqrt(sumx2/ne);
                   5185:   
                   5186:   return 0; 
                   5187: }
                   5188: 
1.126     brouard  5189: /************ Prevalence ********************/
1.227     brouard  5190: 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)
                   5191: {  
                   5192:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5193:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5194:      We still use firstpass and lastpass as another selection.
                   5195:   */
1.126     brouard  5196:  
1.227     brouard  5197:   int i, m, jk, j1, bool, z1,j, iv;
                   5198:   int mi; /* Effective wave */
                   5199:   int iage;
                   5200:   double agebegin, ageend;
                   5201: 
                   5202:   double **prop;
                   5203:   double posprop; 
                   5204:   double  y2; /* in fractional years */
                   5205:   int iagemin, iagemax;
                   5206:   int first; /** to stop verbosity which is redirected to log file */
                   5207: 
                   5208:   iagemin= (int) agemin;
                   5209:   iagemax= (int) agemax;
                   5210:   /*pp=vector(1,nlstate);*/
1.251     brouard  5211:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5212:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5213:   j1=0;
1.222     brouard  5214:   
1.227     brouard  5215:   /*j=cptcoveff;*/
                   5216:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5217:   
1.288     brouard  5218:   first=0;
1.227     brouard  5219:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5220:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5221:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5222:        prop[i][iage]=0.0;
                   5223:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5224:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5225:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5226:     
                   5227:     for (i=1; i<=imx; i++) { /* Each individual */
                   5228:       bool=1;
                   5229:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5230:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5231:        m=mw[mi][i];
                   5232:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5233:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5234:        for (z1=1; z1<=cptcoveff; z1++){
                   5235:          if( Fixed[Tmodelind[z1]]==1){
                   5236:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5237:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5238:              bool=0;
                   5239:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5240:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5241:              bool=0;
                   5242:            }
                   5243:        }
                   5244:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5245:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5246:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5247:          if(m >=firstpass && m <=lastpass){
                   5248:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5249:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5250:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5251:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5252:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5253:                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); 
                   5254:                exit(1);
                   5255:              }
                   5256:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5257:                /*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]]);*/
                   5258:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5259:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5260:              } /* end valid statuses */ 
                   5261:            } /* end selection of dates */
                   5262:          } /* end selection of waves */
                   5263:        } /* end bool */
                   5264:       } /* end wave */
                   5265:     } /* end individual */
                   5266:     for(i=iagemin; i <= iagemax+3; i++){  
                   5267:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5268:        posprop += prop[jk][i]; 
                   5269:       } 
                   5270:       
                   5271:       for(jk=1; jk <=nlstate ; jk++){      
                   5272:        if( i <=  iagemax){ 
                   5273:          if(posprop>=1.e-5){ 
                   5274:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5275:          } else{
1.288     brouard  5276:            if(!first){
                   5277:              first=1;
1.266     brouard  5278:              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]);
                   5279:            }else{
1.288     brouard  5280:              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  5281:            }
                   5282:          }
                   5283:        } 
                   5284:       }/* end jk */ 
                   5285:     }/* end i */ 
1.222     brouard  5286:      /*} *//* end i1 */
1.227     brouard  5287:   } /* end j1 */
1.222     brouard  5288:   
1.227     brouard  5289:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5290:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5291:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5292: }  /* End of prevalence */
1.126     brouard  5293: 
                   5294: /************* Waves Concatenation ***************/
                   5295: 
                   5296: 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)
                   5297: {
1.298     brouard  5298:   /* 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  5299:      Death is a valid wave (if date is known).
                   5300:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5301:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5302:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5303:   */
1.126     brouard  5304: 
1.224     brouard  5305:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5306:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5307:      double sum=0., jmean=0.;*/
1.224     brouard  5308:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5309:   int j, k=0,jk, ju, jl;
                   5310:   double sum=0.;
                   5311:   first=0;
1.214     brouard  5312:   firstwo=0;
1.217     brouard  5313:   firsthree=0;
1.218     brouard  5314:   firstfour=0;
1.164     brouard  5315:   jmin=100000;
1.126     brouard  5316:   jmax=-1;
                   5317:   jmean=0.;
1.224     brouard  5318: 
                   5319: /* Treating live states */
1.214     brouard  5320:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5321:     mi=0;  /* First valid wave */
1.227     brouard  5322:     mli=0; /* Last valid wave */
1.309     brouard  5323:     m=firstpass;  /* Loop on waves */
                   5324:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5325:       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 */
                   5326:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5327:       }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  5328:        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  5329:        mli=m;
1.224     brouard  5330:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5331:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5332:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5333:       }
1.309     brouard  5334:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5335: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5336:        break;
1.224     brouard  5337: #else
1.317   ! brouard  5338:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){ /* no death date and known date of interview, case -2 (vital status unknown is warned later */
1.227     brouard  5339:          if(firsthree == 0){
1.302     brouard  5340:            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  5341:            firsthree=1;
1.317   ! brouard  5342:          }else if(firsthree >=1 && firsthree < 10){
        !          5343:            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);
        !          5344:            firsthree++;
        !          5345:          }else if(firsthree == 10){
        !          5346:            printf("Information, too many Information flags: no more reported to log either\n");
        !          5347:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
        !          5348:            firsthree++;
        !          5349:          }else{
        !          5350:            firsthree++;
1.227     brouard  5351:          }
1.309     brouard  5352:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5353:          mli=m;
                   5354:        }
                   5355:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5356:          nbwarn++;
1.309     brouard  5357:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5358:            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);
                   5359:            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);
                   5360:          }
                   5361:          break;
                   5362:        }
                   5363:        break;
1.224     brouard  5364: #endif
1.227     brouard  5365:       }/* End m >= lastpass */
1.126     brouard  5366:     }/* end while */
1.224     brouard  5367: 
1.227     brouard  5368:     /* 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  5369:     /* After last pass */
1.224     brouard  5370: /* Treating death states */
1.214     brouard  5371:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5372:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5373:       /* } */
1.126     brouard  5374:       mi++;    /* Death is another wave */
                   5375:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5376:       /* Only death is a correct wave */
1.126     brouard  5377:       mw[mi][i]=m;
1.257     brouard  5378:     } /* else not in a death state */
1.224     brouard  5379: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5380:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5381:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5382:        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  5383:          nbwarn++;
                   5384:          if(firstfiv==0){
1.309     brouard  5385:            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  5386:            firstfiv=1;
                   5387:          }else{
1.309     brouard  5388:            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  5389:          }
1.309     brouard  5390:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5391:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5392:          nberr++;
                   5393:          if(firstwo==0){
1.309     brouard  5394:            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  5395:            firstwo=1;
                   5396:          }
1.309     brouard  5397:          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  5398:        }
1.257     brouard  5399:       }else{ /* if date of interview is unknown */
1.227     brouard  5400:        /* death is known but not confirmed by death status at any wave */
                   5401:        if(firstfour==0){
1.309     brouard  5402:          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  5403:          firstfour=1;
                   5404:        }
1.309     brouard  5405:        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  5406:       }
1.224     brouard  5407:     } /* end if date of death is known */
                   5408: #endif
1.309     brouard  5409:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5410:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5411:     if(mi==0){
                   5412:       nbwarn++;
                   5413:       if(first==0){
1.227     brouard  5414:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5415:        first=1;
1.126     brouard  5416:       }
                   5417:       if(first==1){
1.227     brouard  5418:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5419:       }
                   5420:     } /* end mi==0 */
                   5421:   } /* End individuals */
1.214     brouard  5422:   /* wav and mw are no more changed */
1.223     brouard  5423:        
1.317   ! brouard  5424:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
        !          5425:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
        !          5426: 
        !          5427: 
1.126     brouard  5428:   for(i=1; i<=imx; i++){
                   5429:     for(mi=1; mi<wav[i];mi++){
                   5430:       if (stepm <=0)
1.227     brouard  5431:        dh[mi][i]=1;
1.126     brouard  5432:       else{
1.260     brouard  5433:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5434:          if (agedc[i] < 2*AGESUP) {
                   5435:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5436:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5437:            else if(j<0){
                   5438:              nberr++;
                   5439:              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]);
                   5440:              j=1; /* Temporary Dangerous patch */
                   5441:              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);
                   5442:              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]);
                   5443:              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);
                   5444:            }
                   5445:            k=k+1;
                   5446:            if (j >= jmax){
                   5447:              jmax=j;
                   5448:              ijmax=i;
                   5449:            }
                   5450:            if (j <= jmin){
                   5451:              jmin=j;
                   5452:              ijmin=i;
                   5453:            }
                   5454:            sum=sum+j;
                   5455:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5456:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5457:          }
                   5458:        }
                   5459:        else{
                   5460:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5461: /*       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  5462:                                        
1.227     brouard  5463:          k=k+1;
                   5464:          if (j >= jmax) {
                   5465:            jmax=j;
                   5466:            ijmax=i;
                   5467:          }
                   5468:          else if (j <= jmin){
                   5469:            jmin=j;
                   5470:            ijmin=i;
                   5471:          }
                   5472:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5473:          /*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]);*/
                   5474:          if(j<0){
                   5475:            nberr++;
                   5476:            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]);
                   5477:            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]);
                   5478:          }
                   5479:          sum=sum+j;
                   5480:        }
                   5481:        jk= j/stepm;
                   5482:        jl= j -jk*stepm;
                   5483:        ju= j -(jk+1)*stepm;
                   5484:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5485:          if(jl==0){
                   5486:            dh[mi][i]=jk;
                   5487:            bh[mi][i]=0;
                   5488:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5489:                  * to avoid the price of an extra matrix product in likelihood */
                   5490:            dh[mi][i]=jk+1;
                   5491:            bh[mi][i]=ju;
                   5492:          }
                   5493:        }else{
                   5494:          if(jl <= -ju){
                   5495:            dh[mi][i]=jk;
                   5496:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5497:                                 * is higher than the multiple of stepm and negative otherwise.
                   5498:                                 */
                   5499:          }
                   5500:          else{
                   5501:            dh[mi][i]=jk+1;
                   5502:            bh[mi][i]=ju;
                   5503:          }
                   5504:          if(dh[mi][i]==0){
                   5505:            dh[mi][i]=1; /* At least one step */
                   5506:            bh[mi][i]=ju; /* At least one step */
                   5507:            /*  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);*/
                   5508:          }
                   5509:        } /* end if mle */
1.126     brouard  5510:       }
                   5511:     } /* end wave */
                   5512:   }
                   5513:   jmean=sum/k;
                   5514:   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  5515:   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  5516: }
1.126     brouard  5517: 
                   5518: /*********** Tricode ****************************/
1.220     brouard  5519:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5520:  {
                   5521:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5522:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5523:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5524:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5525:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5526:     */
1.130     brouard  5527: 
1.242     brouard  5528:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5529:    int modmaxcovj=0; /* Modality max of covariates j */
                   5530:    int cptcode=0; /* Modality max of covariates j */
                   5531:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5532: 
                   5533: 
1.242     brouard  5534:    /* cptcoveff=0;  */
                   5535:    /* *cptcov=0; */
1.126     brouard  5536:  
1.242     brouard  5537:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5538:    for (k=1; k <= maxncov; k++)
                   5539:      for(j=1; j<=2; j++)
                   5540:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5541: 
1.242     brouard  5542:    /* Loop on covariates without age and products and no quantitative variable */
                   5543:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5544:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5545:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5546:        switch(Fixed[k]) {
                   5547:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5548:         modmaxcovj=0;
                   5549:         modmincovj=0;
1.242     brouard  5550:         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*/
                   5551:           ij=(int)(covar[Tvar[k]][i]);
                   5552:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5553:            * If product of Vn*Vm, still boolean *:
                   5554:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5555:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5556:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5557:              modality of the nth covariate of individual i. */
                   5558:           if (ij > modmaxcovj)
                   5559:             modmaxcovj=ij; 
                   5560:           else if (ij < modmincovj) 
                   5561:             modmincovj=ij; 
1.287     brouard  5562:           if (ij <0 || ij >1 ){
1.311     brouard  5563:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5564:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5565:             fflush(ficlog);
                   5566:             exit(1);
1.287     brouard  5567:           }
                   5568:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5569:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5570:             exit(1);
                   5571:           }else
                   5572:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5573:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5574:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5575:           /* getting the maximum value of the modality of the covariate
                   5576:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5577:              female ies 1, then modmaxcovj=1.
                   5578:           */
                   5579:         } /* end for loop on individuals i */
                   5580:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5581:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5582:         cptcode=modmaxcovj;
                   5583:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5584:         /*for (i=0; i<=cptcode; i++) {*/
                   5585:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5586:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5587:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5588:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5589:             if( j != -1){
                   5590:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5591:                                  covariate for which somebody answered excluding 
                   5592:                                  undefined. Usually 2: 0 and 1. */
                   5593:             }
                   5594:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5595:                                     covariate for which somebody answered including 
                   5596:                                     undefined. Usually 3: -1, 0 and 1. */
                   5597:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5598:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5599:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5600:                        
1.242     brouard  5601:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5602:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5603:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5604:         /* modmincovj=3; modmaxcovj = 7; */
                   5605:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5606:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5607:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5608:         /* nbcode[Tvar[j]][ij]=k; */
                   5609:         /* nbcode[Tvar[j]][1]=0; */
                   5610:         /* nbcode[Tvar[j]][2]=1; */
                   5611:         /* nbcode[Tvar[j]][3]=2; */
                   5612:         /* To be continued (not working yet). */
                   5613:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5614: 
                   5615:         /* 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*/
                   5616:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5617:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5618:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5619:         /*, could be restored in the future */
                   5620:         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  5621:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5622:             break;
                   5623:           }
                   5624:           ij++;
1.287     brouard  5625:           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  5626:           cptcode = ij; /* New max modality for covar j */
                   5627:         } /* end of loop on modality i=-1 to 1 or more */
                   5628:         break;
                   5629:        case 1: /* Testing on varying covariate, could be simple and
                   5630:                * should look at waves or product of fixed *
                   5631:                * varying. No time to test -1, assuming 0 and 1 only */
                   5632:         ij=0;
                   5633:         for(i=0; i<=1;i++){
                   5634:           nbcode[Tvar[k]][++ij]=i;
                   5635:         }
                   5636:         break;
                   5637:        default:
                   5638:         break;
                   5639:        } /* end switch */
                   5640:      } /* end dummy test */
1.311     brouard  5641:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5642:        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*/
                   5643:         if(isnan(covar[Tvar[k]][i])){
                   5644:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5645:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5646:           fflush(ficlog);
                   5647:           exit(1);
                   5648:          }
                   5649:        }
                   5650:      }
1.287     brouard  5651:    } /* 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  5652:   
                   5653:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5654:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5655:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5656:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5657:      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 */ 
                   5658:      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 */
                   5659:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5660:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5661:   
                   5662:    ij=0;
                   5663:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5664:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5665:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5666:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5667:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5668:        /* If product not in single variable we don't print results */
                   5669:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5670:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5671:        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*/
                   5672:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5673:        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 */
                   5674:        if(Fixed[k]!=0)
                   5675:         anyvaryingduminmodel=1;
                   5676:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5677:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5678:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5679:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5680:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5681:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5682:      } 
                   5683:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5684:    /* ij--; */
                   5685:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5686:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5687:                * because they can be excluded from the model and real
                   5688:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5689:    for(j=ij+1; j<= cptcovt; j++){
                   5690:      Tvaraff[j]=0;
                   5691:      Tmodelind[j]=0;
                   5692:    }
                   5693:    for(j=ntveff+1; j<= cptcovt; j++){
                   5694:      TmodelInvind[j]=0;
                   5695:    }
                   5696:    /* To be sorted */
                   5697:    ;
                   5698:  }
1.126     brouard  5699: 
1.145     brouard  5700: 
1.126     brouard  5701: /*********** Health Expectancies ****************/
                   5702: 
1.235     brouard  5703:  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  5704: 
                   5705: {
                   5706:   /* Health expectancies, no variances */
1.164     brouard  5707:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5708:   int nhstepma, nstepma; /* Decreasing with age */
                   5709:   double age, agelim, hf;
                   5710:   double ***p3mat;
                   5711:   double eip;
                   5712: 
1.238     brouard  5713:   /* pstamp(ficreseij); */
1.126     brouard  5714:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5715:   fprintf(ficreseij,"# Age");
                   5716:   for(i=1; i<=nlstate;i++){
                   5717:     for(j=1; j<=nlstate;j++){
                   5718:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5719:     }
                   5720:     fprintf(ficreseij," e%1d. ",i);
                   5721:   }
                   5722:   fprintf(ficreseij,"\n");
                   5723: 
                   5724:   
                   5725:   if(estepm < stepm){
                   5726:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5727:   }
                   5728:   else  hstepm=estepm;   
                   5729:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5730:    * This is mainly to measure the difference between two models: for example
                   5731:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5732:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5733:    * progression in between and thus overestimating or underestimating according
                   5734:    * to the curvature of the survival function. If, for the same date, we 
                   5735:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5736:    * to compare the new estimate of Life expectancy with the same linear 
                   5737:    * hypothesis. A more precise result, taking into account a more precise
                   5738:    * curvature will be obtained if estepm is as small as stepm. */
                   5739: 
                   5740:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5741:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5742:      nhstepm is the number of hstepm from age to agelim 
                   5743:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5744:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5745:      and note for a fixed period like estepm months */
                   5746:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5747:      survival function given by stepm (the optimization length). Unfortunately it
                   5748:      means that if the survival funtion is printed only each two years of age and if
                   5749:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5750:      results. So we changed our mind and took the option of the best precision.
                   5751:   */
                   5752:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5753: 
                   5754:   agelim=AGESUP;
                   5755:   /* If stepm=6 months */
                   5756:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5757:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5758:     
                   5759: /* nhstepm age range expressed in number of stepm */
                   5760:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5761:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5762:   /* if (stepm >= YEARM) hstepm=1;*/
                   5763:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5764:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5765: 
                   5766:   for (age=bage; age<=fage; age ++){ 
                   5767:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5768:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5769:     /* if (stepm >= YEARM) hstepm=1;*/
                   5770:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5771: 
                   5772:     /* If stepm=6 months */
                   5773:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5774:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5775:     
1.235     brouard  5776:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5777:     
                   5778:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5779:     
                   5780:     printf("%d|",(int)age);fflush(stdout);
                   5781:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5782:     
                   5783:     /* Computing expectancies */
                   5784:     for(i=1; i<=nlstate;i++)
                   5785:       for(j=1; j<=nlstate;j++)
                   5786:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5787:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5788:          
                   5789:          /* 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]);*/
                   5790: 
                   5791:        }
                   5792: 
                   5793:     fprintf(ficreseij,"%3.0f",age );
                   5794:     for(i=1; i<=nlstate;i++){
                   5795:       eip=0;
                   5796:       for(j=1; j<=nlstate;j++){
                   5797:        eip +=eij[i][j][(int)age];
                   5798:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5799:       }
                   5800:       fprintf(ficreseij,"%9.4f", eip );
                   5801:     }
                   5802:     fprintf(ficreseij,"\n");
                   5803:     
                   5804:   }
                   5805:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5806:   printf("\n");
                   5807:   fprintf(ficlog,"\n");
                   5808:   
                   5809: }
                   5810: 
1.235     brouard  5811:  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  5812: 
                   5813: {
                   5814:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5815:      to initial status i, ei. .
1.126     brouard  5816:   */
                   5817:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5818:   int nhstepma, nstepma; /* Decreasing with age */
                   5819:   double age, agelim, hf;
                   5820:   double ***p3matp, ***p3matm, ***varhe;
                   5821:   double **dnewm,**doldm;
                   5822:   double *xp, *xm;
                   5823:   double **gp, **gm;
                   5824:   double ***gradg, ***trgradg;
                   5825:   int theta;
                   5826: 
                   5827:   double eip, vip;
                   5828: 
                   5829:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5830:   xp=vector(1,npar);
                   5831:   xm=vector(1,npar);
                   5832:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5833:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5834:   
                   5835:   pstamp(ficresstdeij);
                   5836:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5837:   fprintf(ficresstdeij,"# Age");
                   5838:   for(i=1; i<=nlstate;i++){
                   5839:     for(j=1; j<=nlstate;j++)
                   5840:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5841:     fprintf(ficresstdeij," e%1d. ",i);
                   5842:   }
                   5843:   fprintf(ficresstdeij,"\n");
                   5844: 
                   5845:   pstamp(ficrescveij);
                   5846:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5847:   fprintf(ficrescveij,"# Age");
                   5848:   for(i=1; i<=nlstate;i++)
                   5849:     for(j=1; j<=nlstate;j++){
                   5850:       cptj= (j-1)*nlstate+i;
                   5851:       for(i2=1; i2<=nlstate;i2++)
                   5852:        for(j2=1; j2<=nlstate;j2++){
                   5853:          cptj2= (j2-1)*nlstate+i2;
                   5854:          if(cptj2 <= cptj)
                   5855:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5856:        }
                   5857:     }
                   5858:   fprintf(ficrescveij,"\n");
                   5859:   
                   5860:   if(estepm < stepm){
                   5861:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5862:   }
                   5863:   else  hstepm=estepm;   
                   5864:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5865:    * This is mainly to measure the difference between two models: for example
                   5866:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5867:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5868:    * progression in between and thus overestimating or underestimating according
                   5869:    * to the curvature of the survival function. If, for the same date, we 
                   5870:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5871:    * to compare the new estimate of Life expectancy with the same linear 
                   5872:    * hypothesis. A more precise result, taking into account a more precise
                   5873:    * curvature will be obtained if estepm is as small as stepm. */
                   5874: 
                   5875:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5876:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5877:      nhstepm is the number of hstepm from age to agelim 
                   5878:      nstepm is the number of stepm from age to agelin. 
                   5879:      Look at hpijx to understand the reason of that which relies in memory size
                   5880:      and note for a fixed period like estepm months */
                   5881:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5882:      survival function given by stepm (the optimization length). Unfortunately it
                   5883:      means that if the survival funtion is printed only each two years of age and if
                   5884:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5885:      results. So we changed our mind and took the option of the best precision.
                   5886:   */
                   5887:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5888: 
                   5889:   /* If stepm=6 months */
                   5890:   /* nhstepm age range expressed in number of stepm */
                   5891:   agelim=AGESUP;
                   5892:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5893:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5894:   /* if (stepm >= YEARM) hstepm=1;*/
                   5895:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5896:   
                   5897:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5898:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5899:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5900:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5901:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5902:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5903: 
                   5904:   for (age=bage; age<=fage; age ++){ 
                   5905:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5906:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5907:     /* if (stepm >= YEARM) hstepm=1;*/
                   5908:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5909:                
1.126     brouard  5910:     /* If stepm=6 months */
                   5911:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5912:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5913:     
                   5914:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5915:                
1.126     brouard  5916:     /* Computing  Variances of health expectancies */
                   5917:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5918:        decrease memory allocation */
                   5919:     for(theta=1; theta <=npar; theta++){
                   5920:       for(i=1; i<=npar; i++){ 
1.222     brouard  5921:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5922:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5923:       }
1.235     brouard  5924:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5925:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5926:                        
1.126     brouard  5927:       for(j=1; j<= nlstate; j++){
1.222     brouard  5928:        for(i=1; i<=nlstate; i++){
                   5929:          for(h=0; h<=nhstepm-1; h++){
                   5930:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5931:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5932:          }
                   5933:        }
1.126     brouard  5934:       }
1.218     brouard  5935:                        
1.126     brouard  5936:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5937:        for(h=0; h<=nhstepm-1; h++){
                   5938:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5939:        }
1.126     brouard  5940:     }/* End theta */
                   5941:     
                   5942:     
                   5943:     for(h=0; h<=nhstepm-1; h++)
                   5944:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5945:        for(theta=1; theta <=npar; theta++)
                   5946:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5947:     
1.218     brouard  5948:                
1.222     brouard  5949:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5950:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5951:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5952:                
1.222     brouard  5953:     printf("%d|",(int)age);fflush(stdout);
                   5954:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5955:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5956:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5957:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5958:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5959:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5960:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5961:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5962:       }
                   5963:     }
1.218     brouard  5964:                
1.126     brouard  5965:     /* Computing expectancies */
1.235     brouard  5966:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5967:     for(i=1; i<=nlstate;i++)
                   5968:       for(j=1; j<=nlstate;j++)
1.222     brouard  5969:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5970:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5971:                                        
1.222     brouard  5972:          /* 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  5973:                                        
1.222     brouard  5974:        }
1.269     brouard  5975: 
                   5976:     /* Standard deviation of expectancies ij */                
1.126     brouard  5977:     fprintf(ficresstdeij,"%3.0f",age );
                   5978:     for(i=1; i<=nlstate;i++){
                   5979:       eip=0.;
                   5980:       vip=0.;
                   5981:       for(j=1; j<=nlstate;j++){
1.222     brouard  5982:        eip += eij[i][j][(int)age];
                   5983:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5984:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5985:        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  5986:       }
                   5987:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5988:     }
                   5989:     fprintf(ficresstdeij,"\n");
1.218     brouard  5990:                
1.269     brouard  5991:     /* Variance of expectancies ij */          
1.126     brouard  5992:     fprintf(ficrescveij,"%3.0f",age );
                   5993:     for(i=1; i<=nlstate;i++)
                   5994:       for(j=1; j<=nlstate;j++){
1.222     brouard  5995:        cptj= (j-1)*nlstate+i;
                   5996:        for(i2=1; i2<=nlstate;i2++)
                   5997:          for(j2=1; j2<=nlstate;j2++){
                   5998:            cptj2= (j2-1)*nlstate+i2;
                   5999:            if(cptj2 <= cptj)
                   6000:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6001:          }
1.126     brouard  6002:       }
                   6003:     fprintf(ficrescveij,"\n");
1.218     brouard  6004:                
1.126     brouard  6005:   }
                   6006:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6007:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6008:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6009:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6010:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6011:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6012:   printf("\n");
                   6013:   fprintf(ficlog,"\n");
1.218     brouard  6014:        
1.126     brouard  6015:   free_vector(xm,1,npar);
                   6016:   free_vector(xp,1,npar);
                   6017:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6018:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6019:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6020: }
1.218     brouard  6021:  
1.126     brouard  6022: /************ Variance ******************/
1.235     brouard  6023:  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  6024:  {
1.279     brouard  6025:    /** Variance of health expectancies 
                   6026:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6027:     * double **newm;
                   6028:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6029:     */
1.218     brouard  6030:   
                   6031:    /* int movingaverage(); */
                   6032:    double **dnewm,**doldm;
                   6033:    double **dnewmp,**doldmp;
                   6034:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6035:    int first=0;
1.218     brouard  6036:    int k;
                   6037:    double *xp;
1.279     brouard  6038:    double **gp, **gm;  /**< for var eij */
                   6039:    double ***gradg, ***trgradg; /**< for var eij */
                   6040:    double **gradgp, **trgradgp; /**< for var p point j */
                   6041:    double *gpp, *gmp; /**< for var p point j */
                   6042:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6043:    double ***p3mat;
                   6044:    double age,agelim, hf;
                   6045:    /* double ***mobaverage; */
                   6046:    int theta;
                   6047:    char digit[4];
                   6048:    char digitp[25];
                   6049: 
                   6050:    char fileresprobmorprev[FILENAMELENGTH];
                   6051: 
                   6052:    if(popbased==1){
                   6053:      if(mobilav!=0)
                   6054:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6055:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6056:    }
                   6057:    else 
                   6058:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6059: 
1.218     brouard  6060:    /* if (mobilav!=0) { */
                   6061:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6062:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6063:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6064:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6065:    /*   } */
                   6066:    /* } */
                   6067: 
                   6068:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6069:    sprintf(digit,"%-d",ij);
                   6070:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6071:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6072:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6073:    strcat(fileresprobmorprev,fileresu);
                   6074:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6075:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6076:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6077:    }
                   6078:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6079:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6080:    pstamp(ficresprobmorprev);
                   6081:    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  6082:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6083:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6084:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6085:    }
                   6086:    for(j=1;j<=cptcoveff;j++) 
                   6087:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   6088:    fprintf(ficresprobmorprev,"\n");
                   6089: 
1.218     brouard  6090:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6091:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6092:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6093:      for(i=1; i<=nlstate;i++)
                   6094:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6095:    }  
                   6096:    fprintf(ficresprobmorprev,"\n");
                   6097:   
                   6098:    fprintf(ficgp,"\n# Routine varevsij");
                   6099:    fprintf(ficgp,"\nunset title \n");
                   6100:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6101:    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");
                   6102:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6103: 
1.218     brouard  6104:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6105:    pstamp(ficresvij);
                   6106:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6107:    if(popbased==1)
                   6108:      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);
                   6109:    else
                   6110:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6111:    fprintf(ficresvij,"# Age");
                   6112:    for(i=1; i<=nlstate;i++)
                   6113:      for(j=1; j<=nlstate;j++)
                   6114:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6115:    fprintf(ficresvij,"\n");
                   6116: 
                   6117:    xp=vector(1,npar);
                   6118:    dnewm=matrix(1,nlstate,1,npar);
                   6119:    doldm=matrix(1,nlstate,1,nlstate);
                   6120:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6121:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6122: 
                   6123:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6124:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6125:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6126:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6127:   
1.218     brouard  6128:    if(estepm < stepm){
                   6129:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6130:    }
                   6131:    else  hstepm=estepm;   
                   6132:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6133:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6134:       nhstepm is the number of hstepm from age to agelim 
                   6135:       nstepm is the number of stepm from age to agelim. 
                   6136:       Look at function hpijx to understand why because of memory size limitations, 
                   6137:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6138:       survival function given by stepm (the optimization length). Unfortunately it
                   6139:       means that if the survival funtion is printed every two years of age and if
                   6140:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6141:       results. So we changed our mind and took the option of the best precision.
                   6142:    */
                   6143:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6144:    agelim = AGESUP;
                   6145:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6146:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6147:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6148:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6149:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6150:      gp=matrix(0,nhstepm,1,nlstate);
                   6151:      gm=matrix(0,nhstepm,1,nlstate);
                   6152:                
                   6153:                
                   6154:      for(theta=1; theta <=npar; theta++){
                   6155:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6156:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6157:        }
1.279     brouard  6158:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6159:        * returns into prlim .
1.288     brouard  6160:        */
1.242     brouard  6161:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6162: 
                   6163:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6164:        if (popbased==1) {
                   6165:         if(mobilav ==0){
                   6166:           for(i=1; i<=nlstate;i++)
                   6167:             prlim[i][i]=probs[(int)age][i][ij];
                   6168:         }else{ /* mobilav */ 
                   6169:           for(i=1; i<=nlstate;i++)
                   6170:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6171:         }
                   6172:        }
1.295     brouard  6173:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6174:        */                      
                   6175:        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  6176:        /**< 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  6177:        * at horizon h in state j including mortality.
                   6178:        */
1.218     brouard  6179:        for(j=1; j<= nlstate; j++){
                   6180:         for(h=0; h<=nhstepm; h++){
                   6181:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6182:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6183:         }
                   6184:        }
1.279     brouard  6185:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6186:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6187:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6188:        */
                   6189:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6190:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6191:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6192:        }
                   6193:        
                   6194:        /* Again with minus shift */
1.218     brouard  6195:                        
                   6196:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6197:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6198: 
1.242     brouard  6199:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6200:                        
                   6201:        if (popbased==1) {
                   6202:         if(mobilav ==0){
                   6203:           for(i=1; i<=nlstate;i++)
                   6204:             prlim[i][i]=probs[(int)age][i][ij];
                   6205:         }else{ /* mobilav */ 
                   6206:           for(i=1; i<=nlstate;i++)
                   6207:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6208:         }
                   6209:        }
                   6210:                        
1.235     brouard  6211:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6212:                        
                   6213:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6214:         for(h=0; h<=nhstepm; h++){
                   6215:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6216:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6217:         }
                   6218:        }
                   6219:        /* This for computing probability of death (h=1 means
                   6220:          computed over hstepm matrices product = hstepm*stepm months) 
                   6221:          as a weighted average of prlim.
                   6222:        */
                   6223:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6224:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6225:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6226:        }    
1.279     brouard  6227:        /* end shifting computations */
                   6228: 
                   6229:        /**< Computing gradient matrix at horizon h 
                   6230:        */
1.218     brouard  6231:        for(j=1; j<= nlstate; j++) /* vareij */
                   6232:         for(h=0; h<=nhstepm; h++){
                   6233:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6234:         }
1.279     brouard  6235:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6236:        */
                   6237:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6238:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6239:        }
                   6240:                        
                   6241:      } /* End theta */
1.279     brouard  6242:      
                   6243:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6244:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6245:                
                   6246:      for(h=0; h<=nhstepm; h++) /* veij */
                   6247:        for(j=1; j<=nlstate;j++)
                   6248:         for(theta=1; theta <=npar; theta++)
                   6249:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6250:                
                   6251:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6252:        for(theta=1; theta <=npar; theta++)
                   6253:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6254:      /**< as well as its transposed matrix 
                   6255:       */               
1.218     brouard  6256:                
                   6257:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6258:      for(i=1;i<=nlstate;i++)
                   6259:        for(j=1;j<=nlstate;j++)
                   6260:         vareij[i][j][(int)age] =0.;
1.279     brouard  6261: 
                   6262:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6263:       * and k (nhstepm) formula 15 of article
                   6264:       * Lievre-Brouard-Heathcote
                   6265:       */
                   6266:      
1.218     brouard  6267:      for(h=0;h<=nhstepm;h++){
                   6268:        for(k=0;k<=nhstepm;k++){
                   6269:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6270:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6271:         for(i=1;i<=nlstate;i++)
                   6272:           for(j=1;j<=nlstate;j++)
                   6273:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6274:        }
                   6275:      }
                   6276:                
1.279     brouard  6277:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6278:       * p.j overall mortality formula 49 but computed directly because
                   6279:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6280:       * wix is independent of theta.
                   6281:       */
1.218     brouard  6282:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6283:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6284:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6285:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6286:         varppt[j][i]=doldmp[j][i];
                   6287:      /* end ppptj */
                   6288:      /*  x centered again */
                   6289:                
1.242     brouard  6290:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6291:                
                   6292:      if (popbased==1) {
                   6293:        if(mobilav ==0){
                   6294:         for(i=1; i<=nlstate;i++)
                   6295:           prlim[i][i]=probs[(int)age][i][ij];
                   6296:        }else{ /* mobilav */ 
                   6297:         for(i=1; i<=nlstate;i++)
                   6298:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6299:        }
                   6300:      }
                   6301:                
                   6302:      /* This for computing probability of death (h=1 means
                   6303:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6304:        as a weighted average of prlim.
                   6305:      */
1.235     brouard  6306:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6307:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6308:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6309:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6310:      }    
                   6311:      /* end probability of death */
                   6312:                
                   6313:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6314:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6315:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6316:        for(i=1; i<=nlstate;i++){
                   6317:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6318:        }
                   6319:      } 
                   6320:      fprintf(ficresprobmorprev,"\n");
                   6321:                
                   6322:      fprintf(ficresvij,"%.0f ",age );
                   6323:      for(i=1; i<=nlstate;i++)
                   6324:        for(j=1; j<=nlstate;j++){
                   6325:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6326:        }
                   6327:      fprintf(ficresvij,"\n");
                   6328:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6329:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6330:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6331:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6332:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6333:    } /* End age */
                   6334:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6335:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6336:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6337:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6338:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6339:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6340:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6341:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6342:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6343:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6344:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6345:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6346:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6347:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6348:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6349:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6350:    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);
                   6351:    /*  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  6352:     */
1.218     brouard  6353:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6354:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6355: 
1.218     brouard  6356:    free_vector(xp,1,npar);
                   6357:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6358:    free_matrix(dnewm,1,nlstate,1,npar);
                   6359:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6360:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6361:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6362:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6363:    fclose(ficresprobmorprev);
                   6364:    fflush(ficgp);
                   6365:    fflush(fichtm); 
                   6366:  }  /* end varevsij */
1.126     brouard  6367: 
                   6368: /************ Variance of prevlim ******************/
1.269     brouard  6369:  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  6370: {
1.205     brouard  6371:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6372:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6373: 
1.268     brouard  6374:   double **dnewmpar,**doldm;
1.126     brouard  6375:   int i, j, nhstepm, hstepm;
                   6376:   double *xp;
                   6377:   double *gp, *gm;
                   6378:   double **gradg, **trgradg;
1.208     brouard  6379:   double **mgm, **mgp;
1.126     brouard  6380:   double age,agelim;
                   6381:   int theta;
                   6382:   
                   6383:   pstamp(ficresvpl);
1.288     brouard  6384:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6385:   fprintf(ficresvpl,"# Age ");
                   6386:   if(nresult >=1)
                   6387:     fprintf(ficresvpl," Result# ");
1.126     brouard  6388:   for(i=1; i<=nlstate;i++)
                   6389:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6390:   fprintf(ficresvpl,"\n");
                   6391: 
                   6392:   xp=vector(1,npar);
1.268     brouard  6393:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6394:   doldm=matrix(1,nlstate,1,nlstate);
                   6395:   
                   6396:   hstepm=1*YEARM; /* Every year of age */
                   6397:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6398:   agelim = AGESUP;
                   6399:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6400:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6401:     if (stepm >= YEARM) hstepm=1;
                   6402:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6403:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6404:     mgp=matrix(1,npar,1,nlstate);
                   6405:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6406:     gp=vector(1,nlstate);
                   6407:     gm=vector(1,nlstate);
                   6408: 
                   6409:     for(theta=1; theta <=npar; theta++){
                   6410:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6411:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6412:       }
1.288     brouard  6413:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6414:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6415:       /* else */
                   6416:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6417:       for(i=1;i<=nlstate;i++){
1.126     brouard  6418:        gp[i] = prlim[i][i];
1.208     brouard  6419:        mgp[theta][i] = prlim[i][i];
                   6420:       }
1.126     brouard  6421:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6422:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6423:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6424:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6425:       /* else */
                   6426:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6427:       for(i=1;i<=nlstate;i++){
1.126     brouard  6428:        gm[i] = prlim[i][i];
1.208     brouard  6429:        mgm[theta][i] = prlim[i][i];
                   6430:       }
1.126     brouard  6431:       for(i=1;i<=nlstate;i++)
                   6432:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6433:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6434:     } /* End theta */
                   6435: 
                   6436:     trgradg =matrix(1,nlstate,1,npar);
                   6437: 
                   6438:     for(j=1; j<=nlstate;j++)
                   6439:       for(theta=1; theta <=npar; theta++)
                   6440:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6441:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6442:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6443:     /*   for(j=1; j<=nlstate;j++){ */
                   6444:     /*         printf(" %d ",j); */
                   6445:     /*         for(theta=1; theta <=npar; theta++) */
                   6446:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6447:     /*         printf("\n "); */
                   6448:     /*   } */
                   6449:     /* } */
                   6450:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6451:     /*   printf("\n gradg %d ",(int)age); */
                   6452:     /*   for(j=1; j<=nlstate;j++){ */
                   6453:     /*         printf("%d ",j); */
                   6454:     /*         for(theta=1; theta <=npar; theta++) */
                   6455:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6456:     /*         printf("\n "); */
                   6457:     /*   } */
                   6458:     /* } */
1.126     brouard  6459: 
                   6460:     for(i=1;i<=nlstate;i++)
                   6461:       varpl[i][(int)age] =0.;
1.209     brouard  6462:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6463:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6464:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6465:     }else{
1.268     brouard  6466:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6467:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6468:     }
1.126     brouard  6469:     for(i=1;i<=nlstate;i++)
                   6470:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6471: 
                   6472:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6473:     if(nresult >=1)
                   6474:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6475:     for(i=1; i<=nlstate;i++){
1.126     brouard  6476:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6477:       /* for(j=1;j<=nlstate;j++) */
                   6478:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6479:     }
1.126     brouard  6480:     fprintf(ficresvpl,"\n");
                   6481:     free_vector(gp,1,nlstate);
                   6482:     free_vector(gm,1,nlstate);
1.208     brouard  6483:     free_matrix(mgm,1,npar,1,nlstate);
                   6484:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6485:     free_matrix(gradg,1,npar,1,nlstate);
                   6486:     free_matrix(trgradg,1,nlstate,1,npar);
                   6487:   } /* End age */
                   6488: 
                   6489:   free_vector(xp,1,npar);
                   6490:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6491:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6492: 
                   6493: }
                   6494: 
                   6495: 
                   6496: /************ Variance of backprevalence limit ******************/
1.269     brouard  6497:  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  6498: {
                   6499:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6500:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6501: 
                   6502:   double **dnewmpar,**doldm;
                   6503:   int i, j, nhstepm, hstepm;
                   6504:   double *xp;
                   6505:   double *gp, *gm;
                   6506:   double **gradg, **trgradg;
                   6507:   double **mgm, **mgp;
                   6508:   double age,agelim;
                   6509:   int theta;
                   6510:   
                   6511:   pstamp(ficresvbl);
                   6512:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6513:   fprintf(ficresvbl,"# Age ");
                   6514:   if(nresult >=1)
                   6515:     fprintf(ficresvbl," Result# ");
                   6516:   for(i=1; i<=nlstate;i++)
                   6517:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6518:   fprintf(ficresvbl,"\n");
                   6519: 
                   6520:   xp=vector(1,npar);
                   6521:   dnewmpar=matrix(1,nlstate,1,npar);
                   6522:   doldm=matrix(1,nlstate,1,nlstate);
                   6523:   
                   6524:   hstepm=1*YEARM; /* Every year of age */
                   6525:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6526:   agelim = AGEINF;
                   6527:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6528:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6529:     if (stepm >= YEARM) hstepm=1;
                   6530:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6531:     gradg=matrix(1,npar,1,nlstate);
                   6532:     mgp=matrix(1,npar,1,nlstate);
                   6533:     mgm=matrix(1,npar,1,nlstate);
                   6534:     gp=vector(1,nlstate);
                   6535:     gm=vector(1,nlstate);
                   6536: 
                   6537:     for(theta=1; theta <=npar; theta++){
                   6538:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6539:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6540:       }
                   6541:       if(mobilavproj > 0 )
                   6542:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6543:       else
                   6544:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6545:       for(i=1;i<=nlstate;i++){
                   6546:        gp[i] = bprlim[i][i];
                   6547:        mgp[theta][i] = bprlim[i][i];
                   6548:       }
                   6549:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6550:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6551:        if(mobilavproj > 0 )
                   6552:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6553:        else
                   6554:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6555:       for(i=1;i<=nlstate;i++){
                   6556:        gm[i] = bprlim[i][i];
                   6557:        mgm[theta][i] = bprlim[i][i];
                   6558:       }
                   6559:       for(i=1;i<=nlstate;i++)
                   6560:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6561:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6562:     } /* End theta */
                   6563: 
                   6564:     trgradg =matrix(1,nlstate,1,npar);
                   6565: 
                   6566:     for(j=1; j<=nlstate;j++)
                   6567:       for(theta=1; theta <=npar; theta++)
                   6568:        trgradg[j][theta]=gradg[theta][j];
                   6569:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6570:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6571:     /*   for(j=1; j<=nlstate;j++){ */
                   6572:     /*         printf(" %d ",j); */
                   6573:     /*         for(theta=1; theta <=npar; theta++) */
                   6574:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6575:     /*         printf("\n "); */
                   6576:     /*   } */
                   6577:     /* } */
                   6578:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6579:     /*   printf("\n gradg %d ",(int)age); */
                   6580:     /*   for(j=1; j<=nlstate;j++){ */
                   6581:     /*         printf("%d ",j); */
                   6582:     /*         for(theta=1; theta <=npar; theta++) */
                   6583:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6584:     /*         printf("\n "); */
                   6585:     /*   } */
                   6586:     /* } */
                   6587: 
                   6588:     for(i=1;i<=nlstate;i++)
                   6589:       varbpl[i][(int)age] =0.;
                   6590:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6591:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6592:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6593:     }else{
                   6594:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6595:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6596:     }
                   6597:     for(i=1;i<=nlstate;i++)
                   6598:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6599: 
                   6600:     fprintf(ficresvbl,"%.0f ",age );
                   6601:     if(nresult >=1)
                   6602:       fprintf(ficresvbl,"%d ",nres );
                   6603:     for(i=1; i<=nlstate;i++)
                   6604:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6605:     fprintf(ficresvbl,"\n");
                   6606:     free_vector(gp,1,nlstate);
                   6607:     free_vector(gm,1,nlstate);
                   6608:     free_matrix(mgm,1,npar,1,nlstate);
                   6609:     free_matrix(mgp,1,npar,1,nlstate);
                   6610:     free_matrix(gradg,1,npar,1,nlstate);
                   6611:     free_matrix(trgradg,1,nlstate,1,npar);
                   6612:   } /* End age */
                   6613: 
                   6614:   free_vector(xp,1,npar);
                   6615:   free_matrix(doldm,1,nlstate,1,npar);
                   6616:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6617: 
                   6618: }
                   6619: 
                   6620: /************ Variance of one-step probabilities  ******************/
                   6621: 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  6622:  {
                   6623:    int i, j=0,  k1, l1, tj;
                   6624:    int k2, l2, j1,  z1;
                   6625:    int k=0, l;
                   6626:    int first=1, first1, first2;
                   6627:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6628:    double **dnewm,**doldm;
                   6629:    double *xp;
                   6630:    double *gp, *gm;
                   6631:    double **gradg, **trgradg;
                   6632:    double **mu;
                   6633:    double age, cov[NCOVMAX+1];
                   6634:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6635:    int theta;
                   6636:    char fileresprob[FILENAMELENGTH];
                   6637:    char fileresprobcov[FILENAMELENGTH];
                   6638:    char fileresprobcor[FILENAMELENGTH];
                   6639:    double ***varpij;
                   6640: 
                   6641:    strcpy(fileresprob,"PROB_"); 
                   6642:    strcat(fileresprob,fileres);
                   6643:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6644:      printf("Problem with resultfile: %s\n", fileresprob);
                   6645:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6646:    }
                   6647:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6648:    strcat(fileresprobcov,fileresu);
                   6649:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6650:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6651:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6652:    }
                   6653:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6654:    strcat(fileresprobcor,fileresu);
                   6655:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6656:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6657:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6658:    }
                   6659:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6660:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6661:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6662:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6663:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6664:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6665:    pstamp(ficresprob);
                   6666:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6667:    fprintf(ficresprob,"# Age");
                   6668:    pstamp(ficresprobcov);
                   6669:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6670:    fprintf(ficresprobcov,"# Age");
                   6671:    pstamp(ficresprobcor);
                   6672:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6673:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6674: 
                   6675: 
1.222     brouard  6676:    for(i=1; i<=nlstate;i++)
                   6677:      for(j=1; j<=(nlstate+ndeath);j++){
                   6678:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6679:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6680:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6681:      }  
                   6682:    /* fprintf(ficresprob,"\n");
                   6683:       fprintf(ficresprobcov,"\n");
                   6684:       fprintf(ficresprobcor,"\n");
                   6685:    */
                   6686:    xp=vector(1,npar);
                   6687:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6688:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6689:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6690:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6691:    first=1;
                   6692:    fprintf(ficgp,"\n# Routine varprob");
                   6693:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6694:    fprintf(fichtm,"\n");
                   6695: 
1.288     brouard  6696:    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  6697:    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);
                   6698:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6699: and drawn. It helps understanding how is the covariance between two incidences.\
                   6700:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6701:    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  6702: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6703: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6704: standard deviations wide on each axis. <br>\
                   6705:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6706:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6707: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6708: 
1.222     brouard  6709:    cov[1]=1;
                   6710:    /* tj=cptcoveff; */
1.225     brouard  6711:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6712:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6713:    j1=0;
1.224     brouard  6714:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6715:      if  (cptcovn>0) {
                   6716:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6717:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6718:        fprintf(ficresprob, "**********\n#\n");
                   6719:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6720:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6721:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6722:                        
1.222     brouard  6723:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6724:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6725:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6726:                        
                   6727:                        
1.222     brouard  6728:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6729:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6730:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6731:                        
1.222     brouard  6732:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6733:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6734:        fprintf(ficresprobcor, "**********\n#");    
                   6735:        if(invalidvarcomb[j1]){
                   6736:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6737:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6738:         continue;
                   6739:        }
                   6740:      }
                   6741:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6742:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6743:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6744:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6745:      for (age=bage; age<=fage; age ++){ 
                   6746:        cov[2]=age;
                   6747:        if(nagesqr==1)
                   6748:         cov[3]= age*age;
                   6749:        for (k=1; k<=cptcovn;k++) {
                   6750:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6751:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6752:                                                                    * 1  1 1 1 1
                   6753:                                                                    * 2  2 1 1 1
                   6754:                                                                    * 3  1 2 1 1
                   6755:                                                                    */
                   6756:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6757:        }
                   6758:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6759:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6760:        for (k=1; k<=cptcovprod;k++)
                   6761:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6762:                        
                   6763:                        
1.222     brouard  6764:        for(theta=1; theta <=npar; theta++){
                   6765:         for(i=1; i<=npar; i++)
                   6766:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6767:                                
1.222     brouard  6768:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6769:                                
1.222     brouard  6770:         k=0;
                   6771:         for(i=1; i<= (nlstate); i++){
                   6772:           for(j=1; j<=(nlstate+ndeath);j++){
                   6773:             k=k+1;
                   6774:             gp[k]=pmmij[i][j];
                   6775:           }
                   6776:         }
1.220     brouard  6777:                                
1.222     brouard  6778:         for(i=1; i<=npar; i++)
                   6779:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6780:                                
1.222     brouard  6781:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6782:         k=0;
                   6783:         for(i=1; i<=(nlstate); i++){
                   6784:           for(j=1; j<=(nlstate+ndeath);j++){
                   6785:             k=k+1;
                   6786:             gm[k]=pmmij[i][j];
                   6787:           }
                   6788:         }
1.220     brouard  6789:                                
1.222     brouard  6790:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6791:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6792:        }
1.126     brouard  6793: 
1.222     brouard  6794:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6795:         for(theta=1; theta <=npar; theta++)
                   6796:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6797:                        
1.222     brouard  6798:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6799:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6800:                        
1.222     brouard  6801:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6802:                        
1.222     brouard  6803:        k=0;
                   6804:        for(i=1; i<=(nlstate); i++){
                   6805:         for(j=1; j<=(nlstate+ndeath);j++){
                   6806:           k=k+1;
                   6807:           mu[k][(int) age]=pmmij[i][j];
                   6808:         }
                   6809:        }
                   6810:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6811:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6812:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6813:                        
1.222     brouard  6814:        /*printf("\n%d ",(int)age);
                   6815:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6816:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6817:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6818:         }*/
1.220     brouard  6819:                        
1.222     brouard  6820:        fprintf(ficresprob,"\n%d ",(int)age);
                   6821:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6822:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6823:                        
1.222     brouard  6824:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6825:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6826:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6827:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6828:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6829:        }
                   6830:        i=0;
                   6831:        for (k=1; k<=(nlstate);k++){
                   6832:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6833:           i++;
                   6834:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6835:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6836:           for (j=1; j<=i;j++){
                   6837:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6838:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6839:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6840:           }
                   6841:         }
                   6842:        }/* end of loop for state */
                   6843:      } /* end of loop for age */
                   6844:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6845:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6846:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6847:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6848:     
                   6849:      /* Confidence intervalle of pij  */
                   6850:      /*
                   6851:        fprintf(ficgp,"\nunset parametric;unset label");
                   6852:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6853:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6854:        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);
                   6855:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6856:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6857:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6858:      */
                   6859:                
                   6860:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6861:      first1=1;first2=2;
                   6862:      for (k2=1; k2<=(nlstate);k2++){
                   6863:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6864:         if(l2==k2) continue;
                   6865:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6866:         for (k1=1; k1<=(nlstate);k1++){
                   6867:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6868:             if(l1==k1) continue;
                   6869:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6870:             if(i<=j) continue;
                   6871:             for (age=bage; age<=fage; age ++){ 
                   6872:               if ((int)age %5==0){
                   6873:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6874:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6875:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6876:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6877:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6878:                 c12=cv12/sqrt(v1*v2);
                   6879:                 /* Computing eigen value of matrix of covariance */
                   6880:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6881:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6882:                 if ((lc2 <0) || (lc1 <0) ){
                   6883:                   if(first2==1){
                   6884:                     first1=0;
                   6885:                     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);
                   6886:                   }
                   6887:                   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);
                   6888:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6889:                   /* lc2=fabs(lc2); */
                   6890:                 }
1.220     brouard  6891:                                                                
1.222     brouard  6892:                 /* Eigen vectors */
1.280     brouard  6893:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6894:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6895:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6896:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6897:                 }else
                   6898:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6899:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6900:                 v21=(lc1-v1)/cv12*v11;
                   6901:                 v12=-v21;
                   6902:                 v22=v11;
                   6903:                 tnalp=v21/v11;
                   6904:                 if(first1==1){
                   6905:                   first1=0;
                   6906:                   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);
                   6907:                 }
                   6908:                 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);
                   6909:                 /*printf(fignu*/
                   6910:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6911:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6912:                 if(first==1){
                   6913:                   first=0;
                   6914:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6915:                   fprintf(ficgp,"\nset parametric;unset label");
                   6916:                   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);
                   6917:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6918:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6919:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6920: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6921:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6922:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6923:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6924:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6925:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6926:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6927:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6928:                   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  6929:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6930:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6931:                 }else{
                   6932:                   first=0;
                   6933:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6934:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6935:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6936:                   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  6937:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6938:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6939:                 }/* if first */
                   6940:               } /* age mod 5 */
                   6941:             } /* end loop age */
                   6942:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6943:             first=1;
                   6944:           } /*l12 */
                   6945:         } /* k12 */
                   6946:        } /*l1 */
                   6947:      }/* k1 */
                   6948:    }  /* loop on combination of covariates j1 */
                   6949:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6950:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6951:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6952:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6953:    free_vector(xp,1,npar);
                   6954:    fclose(ficresprob);
                   6955:    fclose(ficresprobcov);
                   6956:    fclose(ficresprobcor);
                   6957:    fflush(ficgp);
                   6958:    fflush(fichtmcov);
                   6959:  }
1.126     brouard  6960: 
                   6961: 
                   6962: /******************* Printing html file ***********/
1.201     brouard  6963: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6964:                  int lastpass, int stepm, int weightopt, char model[],\
                   6965:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  6966:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   6967:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   6968:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  6969:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6970: 
                   6971:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6972:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6973: </ul>");
1.237     brouard  6974:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6975: </ul>", model);
1.214     brouard  6976:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6977:    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",
                   6978:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6979:    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  6980:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6981:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6982:    fprintf(fichtm,"\
                   6983:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6984:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6985:    fprintf(fichtm,"\
1.217     brouard  6986:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6987:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6988:    fprintf(fichtm,"\
1.288     brouard  6989:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6990:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6991:    fprintf(fichtm,"\
1.288     brouard  6992:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6993:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6994:    fprintf(fichtm,"\
1.211     brouard  6995:  - (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  6996:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6997:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6998:    if(prevfcast==1){
                   6999:      fprintf(fichtm,"\
                   7000:  - Prevalence projections by age and states:                           \
1.201     brouard  7001:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7002:    }
1.126     brouard  7003: 
                   7004: 
1.225     brouard  7005:    m=pow(2,cptcoveff);
1.222     brouard  7006:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7007: 
1.317   ! brouard  7008:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7009: 
                   7010:    jj1=0;
                   7011: 
                   7012:    fprintf(fichtm," \n<ul>");
                   7013:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7014:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7015:      if(m != 1 && TKresult[nres]!= k1)
                   7016:        continue;
                   7017:      jj1++;
                   7018:      if (cptcovn > 0) {
                   7019:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7020:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7021:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7022:        }
                   7023:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7024:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7025:        }
                   7026:        fprintf(fichtm,"\">");
                   7027:        
                   7028:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7029:        fprintf(fichtm,"************ Results for covariates");
                   7030:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7031:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7032:        }
                   7033:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7034:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7035:        }
                   7036:        if(invalidvarcomb[k1]){
                   7037:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7038:         continue;
                   7039:        }
                   7040:        fprintf(fichtm,"</a></li>");
                   7041:      } /* cptcovn >0 */
                   7042:    }
1.317   ! brouard  7043:    fprintf(fichtm," \n</ul>");
1.264     brouard  7044: 
1.222     brouard  7045:    jj1=0;
1.237     brouard  7046: 
                   7047:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7048:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7049:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7050:        continue;
1.220     brouard  7051: 
1.222     brouard  7052:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7053:      jj1++;
                   7054:      if (cptcovn > 0) {
1.264     brouard  7055:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7056:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7057:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7058:        }
                   7059:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7060:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7061:        }
                   7062:        fprintf(fichtm,"\"</a>");
                   7063:  
1.222     brouard  7064:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7065:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7066:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7067:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7068:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7069:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7070:        }
1.237     brouard  7071:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7072:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7073:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7074:       }
                   7075:        
1.230     brouard  7076:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  7077:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7078:        if(invalidvarcomb[k1]){
                   7079:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7080:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7081:         continue;
                   7082:        }
                   7083:      }
                   7084:      /* aij, bij */
1.259     brouard  7085:      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  7086: <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  7087:      /* Pij */
1.241     brouard  7088:      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> \
                   7089: <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  7090:      /* Quasi-incidences */
                   7091:      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  7092:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7093:  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  7094: 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> \
                   7095: <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  7096:      /* Survival functions (period) in state j */
                   7097:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7098:        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  7099: <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  7100:      }
                   7101:      /* State specific survival functions (period) */
                   7102:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7103:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7104:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7105:  <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  7106:      }
1.288     brouard  7107:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7108:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7109:        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> \
                   7110: <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  7111:      }
1.296     brouard  7112:      if(prevbcast==1){
1.288     brouard  7113:        /* Backward prevalence in each health state */
1.222     brouard  7114:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7115:         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  7116: <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  7117:        }
1.217     brouard  7118:      }
1.222     brouard  7119:      if(prevfcast==1){
1.288     brouard  7120:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7121:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7122:         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);
                   7123:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7124:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7125:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7126:        }
                   7127:      }
1.296     brouard  7128:      if(prevbcast==1){
1.268     brouard  7129:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7130:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7131:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7132:  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 \
                   7133:  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  7134: 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);
                   7135:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7136:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7137:        }
                   7138:      }
1.220     brouard  7139:         
1.222     brouard  7140:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7141:        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);
                   7142:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7143:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7144:      }
                   7145:      /* } /\* end i1 *\/ */
                   7146:    }/* End k1 */
                   7147:    fprintf(fichtm,"</ul>");
1.126     brouard  7148: 
1.222     brouard  7149:    fprintf(fichtm,"\
1.126     brouard  7150: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7151:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7152:  - 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  7153: But because parameters are usually highly correlated (a higher incidence of disability \
                   7154: and a higher incidence of recovery can give very close observed transition) it might \
                   7155: be very useful to look not only at linear confidence intervals estimated from the \
                   7156: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7157: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7158: covariance matrix of the one-step probabilities. \
                   7159: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7160: 
1.222     brouard  7161:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7162:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7163:    fprintf(fichtm,"\
1.126     brouard  7164:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7165:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7166: 
1.222     brouard  7167:    fprintf(fichtm,"\
1.126     brouard  7168:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7169:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7170:    fprintf(fichtm,"\
1.126     brouard  7171:  - 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): \
                   7172:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7173:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7174:    fprintf(fichtm,"\
1.126     brouard  7175:  - (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): \
                   7176:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7177:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7178:    fprintf(fichtm,"\
1.288     brouard  7179:  - 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  7180:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7181:    fprintf(fichtm,"\
1.128     brouard  7182:  - 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  7183:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7184:    fprintf(fichtm,"\
1.288     brouard  7185:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7186:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7187: 
                   7188: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7189: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7190: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7191: /*     <br>",fileres,fileres,fileres,fileres); */
                   7192: /*  else  */
                   7193: /*    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  7194:    fflush(fichtm);
1.126     brouard  7195: 
1.225     brouard  7196:    m=pow(2,cptcoveff);
1.222     brouard  7197:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7198: 
1.317   ! brouard  7199:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
        !          7200: 
        !          7201:   jj1=0;
        !          7202: 
        !          7203:    fprintf(fichtm," \n<ul>");
        !          7204:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
        !          7205:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
        !          7206:      if(m != 1 && TKresult[nres]!= k1)
        !          7207:        continue;
        !          7208:      jj1++;
        !          7209:      if (cptcovn > 0) {
        !          7210:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
        !          7211:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
        !          7212:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
        !          7213:        }
        !          7214:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          7215:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          7216:        }
        !          7217:        fprintf(fichtm,"\">");
        !          7218:        
        !          7219:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
        !          7220:        fprintf(fichtm,"************ Results for covariates");
        !          7221:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
        !          7222:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
        !          7223:        }
        !          7224:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          7225:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          7226:        }
        !          7227:        if(invalidvarcomb[k1]){
        !          7228:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
        !          7229:         continue;
        !          7230:        }
        !          7231:        fprintf(fichtm,"</a></li>");
        !          7232:      } /* cptcovn >0 */
        !          7233:    }
        !          7234:    fprintf(fichtm," \n</ul>");
        !          7235: 
1.222     brouard  7236:    jj1=0;
1.237     brouard  7237: 
1.241     brouard  7238:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7239:    for(k1=1; k1<=m;k1++){
1.253     brouard  7240:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7241:        continue;
1.222     brouard  7242:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7243:      jj1++;
1.126     brouard  7244:      if (cptcovn > 0) {
1.317   ! brouard  7245:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
        !          7246:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
        !          7247:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
        !          7248:        }
        !          7249:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          7250:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          7251:        }
        !          7252:        fprintf(fichtm,"\"</a>");
        !          7253:        
1.126     brouard  7254:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317   ! brouard  7255:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7256:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317   ! brouard  7257:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7258:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317   ! brouard  7259:        }
1.237     brouard  7260:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7261:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7262:       }
                   7263: 
1.126     brouard  7264:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7265: 
1.222     brouard  7266:        if(invalidvarcomb[k1]){
                   7267:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7268:         continue;
                   7269:        }
1.126     brouard  7270:      }
                   7271:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7272:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7273: 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);
                   7274:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7275:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7276:      }
                   7277:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7278: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7279: true period expectancies (those weighted with period prevalences are also\
                   7280:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7281:  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);
                   7282:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7283:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7284:      /* } /\* end i1 *\/ */
                   7285:    }/* End k1 */
1.241     brouard  7286:   }/* End nres */
1.222     brouard  7287:    fprintf(fichtm,"</ul>");
                   7288:    fflush(fichtm);
1.126     brouard  7289: }
                   7290: 
                   7291: /******************* Gnuplot file **************/
1.296     brouard  7292: 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  7293: 
                   7294:   char dirfileres[132],optfileres[132];
1.264     brouard  7295:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7296:   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  7297:   int lv=0, vlv=0, kl=0;
1.130     brouard  7298:   int ng=0;
1.201     brouard  7299:   int vpopbased;
1.223     brouard  7300:   int ioffset; /* variable offset for columns */
1.270     brouard  7301:   int iyearc=1; /* variable column for year of projection  */
                   7302:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7303:   int nres=0; /* Index of resultline */
1.266     brouard  7304:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7305: 
1.126     brouard  7306: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7307: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7308: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7309: /*   } */
                   7310: 
                   7311:   /*#ifdef windows */
                   7312:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7313:   /*#endif */
1.225     brouard  7314:   m=pow(2,cptcoveff);
1.126     brouard  7315: 
1.274     brouard  7316:   /* diagram of the model */
                   7317:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7318:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7319:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7320:   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);
                   7321: 
                   7322:   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);
                   7323:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7324:   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);
                   7325:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7326:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7327:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7328:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7329: 
1.202     brouard  7330:   /* Contribution to likelihood */
                   7331:   /* Plot the probability implied in the likelihood */
1.223     brouard  7332:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7333:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7334:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7335:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7336: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7337:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7338: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7339:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7340:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7341:   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));
                   7342:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7343:   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));
                   7344:   for (i=1; i<= nlstate ; i ++) {
                   7345:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7346:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7347:     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);
                   7348:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7349:       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);
                   7350:     }
                   7351:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7352:   }
                   7353:   /* 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 */               
                   7354:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7355:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7356:   fprintf(ficgp,"\nset out;unset log\n");
                   7357:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7358: 
1.126     brouard  7359:   strcpy(dirfileres,optionfilefiname);
                   7360:   strcpy(optfileres,"vpl");
1.223     brouard  7361:   /* 1eme*/
1.238     brouard  7362:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7363:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7364:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7365:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7366:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7367:          continue;
                   7368:        /* We are interested in selected combination by the resultline */
1.246     brouard  7369:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7370:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7371:        strcpy(gplotlabel,"(");
1.238     brouard  7372:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7373:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7374:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7375:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7376:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7377:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7378:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7379:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7380:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7381:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7382:        }
                   7383:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7384:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7385:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7386:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7387:        }
                   7388:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7389:        /* printf("\n#\n"); */
1.238     brouard  7390:        fprintf(ficgp,"\n#\n");
                   7391:        if(invalidvarcomb[k1]){
1.260     brouard  7392:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7393:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7394:          continue;
                   7395:        }
1.235     brouard  7396:       
1.241     brouard  7397:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7398:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7399:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7400:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7401:        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);
                   7402:        /* 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); */
                   7403:       /* k1-1 error should be nres-1*/
1.238     brouard  7404:        for (i=1; i<= nlstate ; i ++) {
                   7405:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7406:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7407:        }
1.288     brouard  7408:        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  7409:        for (i=1; i<= nlstate ; i ++) {
                   7410:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7411:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7412:        } 
1.260     brouard  7413:        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  7414:        for (i=1; i<= nlstate ; i ++) {
                   7415:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7416:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7417:        }  
1.265     brouard  7418:        /* 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)); */
                   7419:        
                   7420:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7421:         if(cptcoveff ==0){
1.271     brouard  7422:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7423:        }else{
                   7424:          kl=0;
                   7425:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7426:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7427:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7428:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7429:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7430:            vlv= nbcode[Tvaraff[k]][lv];
                   7431:            kl++;
                   7432:            /* 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 *\/ */
                   7433:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7434:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7435:            /* ''  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*/
                   7436:            if(k==cptcoveff){
                   7437:              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], \
                   7438:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7439:            }else{
                   7440:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7441:              kl++;
                   7442:            }
                   7443:          } /* end covariate */
                   7444:        } /* end if no covariate */
                   7445: 
1.296     brouard  7446:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7447:          /* 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  7448:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7449:          if(cptcoveff ==0){
1.245     brouard  7450:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7451:          }else{
                   7452:            kl=0;
                   7453:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7454:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7455:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7456:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7457:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7458:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7459:              kl++;
1.238     brouard  7460:              /* 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 *\/ */
                   7461:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7462:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7463:              /* ''  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*/
                   7464:              if(k==cptcoveff){
1.245     brouard  7465:                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  7466:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7467:              }else{
                   7468:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7469:                kl++;
                   7470:              }
                   7471:            } /* end covariate */
                   7472:          } /* end if no covariate */
1.296     brouard  7473:          if(prevbcast == 1){
1.268     brouard  7474:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7475:            /* k1-1 error should be nres-1*/
                   7476:            for (i=1; i<= nlstate ; i ++) {
                   7477:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7478:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7479:            }
1.271     brouard  7480:            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  7481:            for (i=1; i<= nlstate ; i ++) {
                   7482:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7483:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7484:            } 
1.276     brouard  7485:            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  7486:            for (i=1; i<= nlstate ; i ++) {
                   7487:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7488:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7489:            } 
1.274     brouard  7490:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7491:          } /* end if backprojcast */
1.296     brouard  7492:        } /* end if prevbcast */
1.276     brouard  7493:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7494:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7495:       } /* nres */
1.201     brouard  7496:     } /* k1 */
                   7497:   } /* cpt */
1.235     brouard  7498: 
                   7499:   
1.126     brouard  7500:   /*2 eme*/
1.238     brouard  7501:   for (k1=1; k1<= m ; k1 ++){  
                   7502:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7503:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7504:        continue;
                   7505:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7506:       strcpy(gplotlabel,"(");
1.238     brouard  7507:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7508:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7509:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7510:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7511:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7512:        vlv= nbcode[Tvaraff[k]][lv];
                   7513:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7514:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7515:       }
1.237     brouard  7516:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7517:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7518:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7519:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7520:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7521:       }
1.264     brouard  7522:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7523:       fprintf(ficgp,"\n#\n");
1.223     brouard  7524:       if(invalidvarcomb[k1]){
                   7525:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7526:        continue;
                   7527:       }
1.219     brouard  7528:                        
1.241     brouard  7529:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7530:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7531:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7532:        if(vpopbased==0){
1.238     brouard  7533:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7534:        }else
1.238     brouard  7535:          fprintf(ficgp,"\nreplot ");
                   7536:        for (i=1; i<= nlstate+1 ; i ++) {
                   7537:          k=2*i;
1.261     brouard  7538:          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  7539:          for (j=1; j<= nlstate+1 ; j ++) {
                   7540:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7541:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7542:          }   
                   7543:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7544:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7545:          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  7546:          for (j=1; j<= nlstate+1 ; j ++) {
                   7547:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7548:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7549:          }   
                   7550:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7551:          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  7552:          for (j=1; j<= nlstate+1 ; j ++) {
                   7553:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7554:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7555:          }   
                   7556:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7557:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7558:        } /* state */
                   7559:       } /* vpopbased */
1.264     brouard  7560:       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  7561:     } /* end nres */
                   7562:   } /* k1 end 2 eme*/
                   7563:        
                   7564:        
                   7565:   /*3eme*/
                   7566:   for (k1=1; k1<= m ; k1 ++){
                   7567:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7568:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7569:        continue;
                   7570: 
                   7571:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7572:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7573:        strcpy(gplotlabel,"(");
1.238     brouard  7574:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7575:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7576:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7577:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7578:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7579:          vlv= nbcode[Tvaraff[k]][lv];
                   7580:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7581:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7582:        }
                   7583:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7584:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7585:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7586:        }       
1.264     brouard  7587:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7588:        fprintf(ficgp,"\n#\n");
                   7589:        if(invalidvarcomb[k1]){
                   7590:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7591:          continue;
                   7592:        }
                   7593:                        
                   7594:        /*       k=2+nlstate*(2*cpt-2); */
                   7595:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7596:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7597:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7598:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7599: 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  7600:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7601:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7602:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7603:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7604:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7605:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7606:                                
1.238     brouard  7607:        */
                   7608:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7609:          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  7610:          /*    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  7611:                                
1.238     brouard  7612:        } 
1.261     brouard  7613:        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  7614:       }
1.264     brouard  7615:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7616:     } /* end nres */
                   7617:   } /* end kl 3eme */
1.126     brouard  7618:   
1.223     brouard  7619:   /* 4eme */
1.201     brouard  7620:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7621:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7622:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7623:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7624:        continue;
1.238     brouard  7625:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7626:        strcpy(gplotlabel,"(");
1.238     brouard  7627:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7628:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7629:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7630:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7631:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7632:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7633:          vlv= nbcode[Tvaraff[k]][lv];
                   7634:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7635:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7636:        }
                   7637:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7638:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7639:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7640:        }       
1.264     brouard  7641:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7642:        fprintf(ficgp,"\n#\n");
                   7643:        if(invalidvarcomb[k1]){
                   7644:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7645:          continue;
1.223     brouard  7646:        }
1.238     brouard  7647:       
1.241     brouard  7648:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7649:        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  7650:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7651: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7652:        k=3;
                   7653:        for (i=1; i<= nlstate ; i ++){
                   7654:          if(i==1){
                   7655:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7656:          }else{
                   7657:            fprintf(ficgp,", '' ");
                   7658:          }
                   7659:          l=(nlstate+ndeath)*(i-1)+1;
                   7660:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7661:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7662:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7663:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7664:        } /* nlstate */
1.264     brouard  7665:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7666:       } /* end cpt state*/ 
                   7667:     } /* end nres */
                   7668:   } /* end covariate k1 */  
                   7669: 
1.220     brouard  7670: /* 5eme */
1.201     brouard  7671:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7672:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7673:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7674:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7675:        continue;
1.238     brouard  7676:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7677:        strcpy(gplotlabel,"(");
1.238     brouard  7678:        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);
                   7679:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7680:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7681:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7682:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7683:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7684:          vlv= nbcode[Tvaraff[k]][lv];
                   7685:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7686:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7687:        }
                   7688:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7689:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7690:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7691:        }       
1.264     brouard  7692:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7693:        fprintf(ficgp,"\n#\n");
                   7694:        if(invalidvarcomb[k1]){
                   7695:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7696:          continue;
                   7697:        }
1.227     brouard  7698:       
1.241     brouard  7699:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7700:        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  7701:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7702: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7703:        k=3;
                   7704:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7705:          if(j==1)
                   7706:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7707:          else
                   7708:            fprintf(ficgp,", '' ");
                   7709:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7710:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7711:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7712:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7713:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7714:        } /* nlstate */
                   7715:        fprintf(ficgp,", '' ");
                   7716:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7717:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7718:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7719:          if(j < nlstate)
                   7720:            fprintf(ficgp,"$%d +",k+l);
                   7721:          else
                   7722:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7723:        }
1.264     brouard  7724:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7725:       } /* end cpt state*/ 
                   7726:     } /* end covariate */  
                   7727:   } /* end nres */
1.227     brouard  7728:   
1.220     brouard  7729: /* 6eme */
1.202     brouard  7730:   /* CV preval stable (period) for each covariate */
1.237     brouard  7731:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7732:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7733:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7734:       continue;
1.255     brouard  7735:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7736:       strcpy(gplotlabel,"(");      
1.288     brouard  7737:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7738:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7739:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7740:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7741:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7742:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7743:        vlv= nbcode[Tvaraff[k]][lv];
                   7744:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7745:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7746:       }
1.237     brouard  7747:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7748:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7749:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7750:       }        
1.264     brouard  7751:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7752:       fprintf(ficgp,"\n#\n");
1.223     brouard  7753:       if(invalidvarcomb[k1]){
1.227     brouard  7754:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7755:        continue;
1.223     brouard  7756:       }
1.227     brouard  7757:       
1.241     brouard  7758:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7759:       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  7760:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7761: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7762:       k=3; /* Offset */
1.255     brouard  7763:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7764:        if(i==1)
                   7765:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7766:        else
                   7767:          fprintf(ficgp,", '' ");
1.255     brouard  7768:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7769:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7770:        for (j=2; j<= nlstate ; j ++)
                   7771:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7772:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7773:       } /* nlstate */
1.264     brouard  7774:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7775:     } /* end cpt state*/ 
                   7776:   } /* end covariate */  
1.227     brouard  7777:   
                   7778:   
1.220     brouard  7779: /* 7eme */
1.296     brouard  7780:   if(prevbcast == 1){
1.288     brouard  7781:     /* CV backward prevalence  for each covariate */
1.237     brouard  7782:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7783:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7784:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7785:        continue;
1.268     brouard  7786:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7787:        strcpy(gplotlabel,"(");      
1.288     brouard  7788:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7789:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7790:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7791:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7792:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7793:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7794:          vlv= nbcode[Tvaraff[k]][lv];
                   7795:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7796:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7797:        }
1.237     brouard  7798:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7799:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7800:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7801:        }       
1.264     brouard  7802:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7803:        fprintf(ficgp,"\n#\n");
                   7804:        if(invalidvarcomb[k1]){
                   7805:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7806:          continue;
                   7807:        }
                   7808:        
1.241     brouard  7809:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7810:        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  7811:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7812: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7813:        k=3; /* Offset */
1.268     brouard  7814:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7815:          if(i==1)
                   7816:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7817:          else
                   7818:            fprintf(ficgp,", '' ");
                   7819:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7820:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7821:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7822:          /* 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  7823:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7824:          /* for (j=2; j<= nlstate ; j ++) */
                   7825:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7826:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7827:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7828:        } /* nlstate */
1.264     brouard  7829:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7830:       } /* end cpt state*/ 
                   7831:     } /* end covariate */  
1.296     brouard  7832:   } /* End if prevbcast */
1.218     brouard  7833:   
1.223     brouard  7834:   /* 8eme */
1.218     brouard  7835:   if(prevfcast==1){
1.288     brouard  7836:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7837:     
1.237     brouard  7838:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7839:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7840:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7841:        continue;
1.211     brouard  7842:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7843:        strcpy(gplotlabel,"(");      
1.288     brouard  7844:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7845:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7846:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7847:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7848:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7849:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7850:          vlv= nbcode[Tvaraff[k]][lv];
                   7851:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7852:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7853:        }
1.237     brouard  7854:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7855:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7856:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7857:        }       
1.264     brouard  7858:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7859:        fprintf(ficgp,"\n#\n");
                   7860:        if(invalidvarcomb[k1]){
                   7861:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7862:          continue;
                   7863:        }
                   7864:        
                   7865:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7866:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7867:        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  7868:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7869: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7870: 
                   7871:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7872:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7873:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7874:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7875:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7876:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7877:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7878:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7879:          if(i==istart){
1.227     brouard  7880:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7881:          }else{
                   7882:            fprintf(ficgp,",\\\n '' ");
                   7883:          }
                   7884:          if(cptcoveff ==0){ /* No covariate */
                   7885:            ioffset=2; /* Age is in 2 */
                   7886:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7887:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7888:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7889:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7890:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7891:            if(i==nlstate+1){
1.270     brouard  7892:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7893:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7894:              fprintf(ficgp,",\\\n '' ");
                   7895:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7896:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7897:                     offyear,                           \
1.268     brouard  7898:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7899:            }else
1.227     brouard  7900:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7901:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7902:          }else{ /* more than 2 covariates */
1.270     brouard  7903:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7904:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7905:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7906:            iyearc=ioffset-1;
                   7907:            iagec=ioffset;
1.227     brouard  7908:            fprintf(ficgp," u %d:(",ioffset); 
                   7909:            kl=0;
                   7910:            strcpy(gplotcondition,"(");
                   7911:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7912:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7913:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7914:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7915:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7916:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7917:              kl++;
                   7918:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7919:              kl++;
                   7920:              if(k <cptcoveff && cptcoveff>1)
                   7921:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7922:            }
                   7923:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7924:            /* 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 *\/ */
                   7925:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7926:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7927:            /* ''  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*/
                   7928:            if(i==nlstate+1){
1.270     brouard  7929:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7930:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7931:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7932:              fprintf(ficgp," u %d:(",iagec); 
                   7933:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7934:                      iyearc, iagec, offyear,                           \
                   7935:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7936: /*  '' 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  7937:            }else{
                   7938:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7939:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7940:            }
                   7941:          } /* end if covariate */
                   7942:        } /* nlstate */
1.264     brouard  7943:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7944:       } /* end cpt state*/
                   7945:     } /* end covariate */
                   7946:   } /* End if prevfcast */
1.227     brouard  7947:   
1.296     brouard  7948:   if(prevbcast==1){
1.268     brouard  7949:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7950:     
                   7951:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7952:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7953:       if(m != 1 && TKresult[nres]!= k1)
                   7954:        continue;
                   7955:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7956:        strcpy(gplotlabel,"(");      
                   7957:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7958:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7959:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7960:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7961:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7962:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7963:          vlv= nbcode[Tvaraff[k]][lv];
                   7964:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7965:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7966:        }
                   7967:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7968:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7969:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7970:        }       
                   7971:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7972:        fprintf(ficgp,"\n#\n");
                   7973:        if(invalidvarcomb[k1]){
                   7974:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7975:          continue;
                   7976:        }
                   7977:        
                   7978:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7979:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7980:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7981:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7982: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7983: 
                   7984:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7985:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7986:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7987:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7988:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7989:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7990:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7991:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7992:          if(i==istart){
                   7993:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7994:          }else{
                   7995:            fprintf(ficgp,",\\\n '' ");
                   7996:          }
                   7997:          if(cptcoveff ==0){ /* No covariate */
                   7998:            ioffset=2; /* Age is in 2 */
                   7999:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8000:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8001:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8002:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8003:            fprintf(ficgp," u %d:(", ioffset); 
                   8004:            if(i==nlstate+1){
1.270     brouard  8005:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8006:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8007:              fprintf(ficgp,",\\\n '' ");
                   8008:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8009:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8010:                     offbyear,                          \
                   8011:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8012:            }else
                   8013:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8014:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8015:          }else{ /* more than 2 covariates */
1.270     brouard  8016:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8017:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8018:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8019:            iyearc=ioffset-1;
                   8020:            iagec=ioffset;
1.268     brouard  8021:            fprintf(ficgp," u %d:(",ioffset); 
                   8022:            kl=0;
                   8023:            strcpy(gplotcondition,"(");
                   8024:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8025:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8026:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8027:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8028:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8029:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8030:              kl++;
                   8031:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8032:              kl++;
                   8033:              if(k <cptcoveff && cptcoveff>1)
                   8034:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8035:            }
                   8036:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8037:            /* 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 *\/ */
                   8038:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8039:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8040:            /* ''  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*/
                   8041:            if(i==nlstate+1){
1.270     brouard  8042:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8043:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8044:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8045:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8046:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8047:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8048:                      iyearc,iagec,offbyear,                            \
                   8049:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8050: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8051:            }else{
                   8052:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8053:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8054:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8055:            }
                   8056:          } /* end if covariate */
                   8057:        } /* nlstate */
                   8058:        fprintf(ficgp,"\nset out; unset label;\n");
                   8059:       } /* end cpt state*/
                   8060:     } /* end covariate */
1.296     brouard  8061:   } /* End if prevbcast */
1.268     brouard  8062:   
1.227     brouard  8063:   
1.238     brouard  8064:   /* 9eme writing MLE parameters */
                   8065:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8066:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8067:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8068:     for(k=1; k <=(nlstate+ndeath); k++){
                   8069:       if (k != i) {
1.227     brouard  8070:        fprintf(ficgp,"#   current state %d\n",k);
                   8071:        for(j=1; j <=ncovmodel; j++){
                   8072:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8073:          jk++; 
                   8074:        }
                   8075:        fprintf(ficgp,"\n");
1.126     brouard  8076:       }
                   8077:     }
1.223     brouard  8078:   }
1.187     brouard  8079:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8080:   
1.145     brouard  8081:   /*goto avoid;*/
1.238     brouard  8082:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8083:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8084:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8085:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8086:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8087:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8088:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8089:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8090:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8091:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8092:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8093:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8094:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8095:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8096:   fprintf(ficgp,"#\n");
1.223     brouard  8097:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8098:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8099:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8100:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8101:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8102:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8103:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8104:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8105:        continue;
1.264     brouard  8106:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8107:       strcpy(gplotlabel,"(");
1.276     brouard  8108:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8109:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8110:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8111:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8112:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8113:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8114:        vlv= nbcode[Tvaraff[k]][lv];
                   8115:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8116:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8117:       }
1.237     brouard  8118:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8119:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8120:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8121:       }        
1.264     brouard  8122:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8123:       fprintf(ficgp,"\n#\n");
1.264     brouard  8124:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8125:       fprintf(ficgp,"\nset key outside ");
                   8126:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8127:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8128:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8129:       if (ng==1){
                   8130:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8131:        fprintf(ficgp,"\nunset log y");
                   8132:       }else if (ng==2){
                   8133:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8134:        fprintf(ficgp,"\nset log y");
                   8135:       }else if (ng==3){
                   8136:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8137:        fprintf(ficgp,"\nset log y");
                   8138:       }else
                   8139:        fprintf(ficgp,"\nunset title ");
                   8140:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8141:       i=1;
                   8142:       for(k2=1; k2<=nlstate; k2++) {
                   8143:        k3=i;
                   8144:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8145:          if (k != k2){
                   8146:            switch( ng) {
                   8147:            case 1:
                   8148:              if(nagesqr==0)
                   8149:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8150:              else /* nagesqr =1 */
                   8151:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8152:              break;
                   8153:            case 2: /* ng=2 */
                   8154:              if(nagesqr==0)
                   8155:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8156:              else /* nagesqr =1 */
                   8157:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8158:              break;
                   8159:            case 3:
                   8160:              if(nagesqr==0)
                   8161:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8162:              else /* nagesqr =1 */
                   8163:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8164:              break;
                   8165:            }
                   8166:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8167:            ijp=1; /* product no age */
                   8168:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8169:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8170:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8171:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8172:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8173:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8174:                    if(DummyV[j]==0){
                   8175:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8176:                    }else{ /* quantitative */
                   8177:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8178:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8179:                    }
                   8180:                    ij++;
1.237     brouard  8181:                  }
1.268     brouard  8182:                } 
                   8183:              }else if(cptcovprod >0){
                   8184:                if(j==Tprod[ijp]) { /* */ 
                   8185:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8186:                  if(ijp <=cptcovprod) { /* Product */
                   8187:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8188:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8189:                        /* 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)]); */
                   8190:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8191:                      }else{ /* Vn is dummy and Vm is quanti */
                   8192:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8193:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8194:                      }
                   8195:                    }else{ /* Vn*Vm Vn is quanti */
                   8196:                      if(DummyV[Tvard[ijp][2]]==0){
                   8197:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8198:                      }else{ /* Both quanti */
                   8199:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8200:                      }
1.237     brouard  8201:                    }
1.268     brouard  8202:                    ijp++;
1.237     brouard  8203:                  }
1.268     brouard  8204:                } /* end Tprod */
1.237     brouard  8205:              } else{  /* simple covariate */
1.264     brouard  8206:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8207:                if(Dummy[j]==0){
                   8208:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8209:                }else{ /* quantitative */
                   8210:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8211:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8212:                }
1.237     brouard  8213:              } /* end simple */
                   8214:            } /* end j */
1.223     brouard  8215:          }else{
                   8216:            i=i-ncovmodel;
                   8217:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8218:              fprintf(ficgp," (1.");
                   8219:          }
1.227     brouard  8220:          
1.223     brouard  8221:          if(ng != 1){
                   8222:            fprintf(ficgp,")/(1");
1.227     brouard  8223:            
1.264     brouard  8224:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8225:              if(nagesqr==0)
1.264     brouard  8226:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8227:              else /* nagesqr =1 */
1.264     brouard  8228:                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  8229:               
1.223     brouard  8230:              ij=1;
                   8231:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8232:                 if(cptcovage >0){ 
                   8233:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8234:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8235:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8236:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8237:                       ij++;
                   8238:                     }
                   8239:                   }
                   8240:                 }else
                   8241:                   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  8242:              }
                   8243:              fprintf(ficgp,")");
                   8244:            }
                   8245:            fprintf(ficgp,")");
                   8246:            if(ng ==2)
1.276     brouard  8247:              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  8248:            else /* ng= 3 */
1.276     brouard  8249:              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  8250:          }else{ /* end ng <> 1 */
                   8251:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8252:              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  8253:          }
                   8254:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8255:            fprintf(ficgp,",");
                   8256:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8257:            fprintf(ficgp,",");
                   8258:          i=i+ncovmodel;
                   8259:        } /* end k */
                   8260:       } /* end k2 */
1.276     brouard  8261:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8262:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8263:     } /* end k1 */
1.223     brouard  8264:   } /* end ng */
                   8265:   /* avoid: */
                   8266:   fflush(ficgp); 
1.126     brouard  8267: }  /* end gnuplot */
                   8268: 
                   8269: 
                   8270: /*************** Moving average **************/
1.219     brouard  8271: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8272:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8273:    
1.222     brouard  8274:    int i, cpt, cptcod;
                   8275:    int modcovmax =1;
                   8276:    int mobilavrange, mob;
                   8277:    int iage=0;
1.288     brouard  8278:    int firstA1=0, firstA2=0;
1.222     brouard  8279: 
1.266     brouard  8280:    double sum=0., sumr=0.;
1.222     brouard  8281:    double age;
1.266     brouard  8282:    double *sumnewp, *sumnewm, *sumnewmr;
                   8283:    double *agemingood, *agemaxgood; 
                   8284:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8285:   
                   8286:   
1.278     brouard  8287:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8288:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8289: 
                   8290:    sumnewp = vector(1,ncovcombmax);
                   8291:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8292:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8293:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8294:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8295:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8296:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8297: 
                   8298:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8299:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8300:      sumnewp[cptcod]=0.;
1.266     brouard  8301:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8302:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8303:    }
                   8304:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8305:   
1.266     brouard  8306:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8307:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8308:      else mobilavrange=mobilav;
                   8309:      for (age=bage; age<=fage; age++)
                   8310:        for (i=1; i<=nlstate;i++)
                   8311:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8312:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8313:      /* We keep the original values on the extreme ages bage, fage and for 
                   8314:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8315:        we use a 5 terms etc. until the borders are no more concerned. 
                   8316:      */ 
                   8317:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8318:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8319:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8320:           sumnewm[cptcod]=0.;
                   8321:           for (i=1; i<=nlstate;i++){
1.222     brouard  8322:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8323:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8324:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8325:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8326:             }
                   8327:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8328:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8329:           } /* end i */
                   8330:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8331:         } /* end cptcod */
1.222     brouard  8332:        }/* end age */
                   8333:      }/* end mob */
1.266     brouard  8334:    }else{
                   8335:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8336:      return -1;
1.266     brouard  8337:    }
                   8338: 
                   8339:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8340:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8341:      if(invalidvarcomb[cptcod]){
                   8342:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8343:        continue;
                   8344:      }
1.219     brouard  8345: 
1.266     brouard  8346:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8347:        sumnewm[cptcod]=0.;
                   8348:        sumnewmr[cptcod]=0.;
                   8349:        for (i=1; i<=nlstate;i++){
                   8350:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8351:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8352:        }
                   8353:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8354:         agemingoodr[cptcod]=age;
                   8355:        }
                   8356:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8357:           agemingood[cptcod]=age;
                   8358:        }
                   8359:      } /* age */
                   8360:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8361:        sumnewm[cptcod]=0.;
1.266     brouard  8362:        sumnewmr[cptcod]=0.;
1.222     brouard  8363:        for (i=1; i<=nlstate;i++){
                   8364:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8365:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8366:        }
                   8367:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8368:         agemaxgoodr[cptcod]=age;
1.222     brouard  8369:        }
                   8370:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8371:         agemaxgood[cptcod]=age;
                   8372:        }
                   8373:      } /* age */
                   8374:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8375:      /* but they will change */
1.288     brouard  8376:      firstA1=0;firstA2=0;
1.266     brouard  8377:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8378:        sumnewm[cptcod]=0.;
                   8379:        sumnewmr[cptcod]=0.;
                   8380:        for (i=1; i<=nlstate;i++){
                   8381:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8382:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8383:        }
                   8384:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8385:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8386:           agemaxgoodr[cptcod]=age;  /* age min */
                   8387:           for (i=1; i<=nlstate;i++)
                   8388:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8389:         }else{ /* bad we change the value with the values of good ages */
                   8390:           for (i=1; i<=nlstate;i++){
                   8391:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8392:           } /* i */
                   8393:         } /* end bad */
                   8394:        }else{
                   8395:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8396:           agemaxgood[cptcod]=age;
                   8397:         }else{ /* bad we change the value with the values of good ages */
                   8398:           for (i=1; i<=nlstate;i++){
                   8399:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8400:           } /* i */
                   8401:         } /* end bad */
                   8402:        }/* end else */
                   8403:        sum=0.;sumr=0.;
                   8404:        for (i=1; i<=nlstate;i++){
                   8405:         sum+=mobaverage[(int)age][i][cptcod];
                   8406:         sumr+=probs[(int)age][i][cptcod];
                   8407:        }
                   8408:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8409:         if(!firstA1){
                   8410:           firstA1=1;
                   8411:           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);
                   8412:         }
                   8413:         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  8414:        } /* end bad */
                   8415:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8416:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8417:         if(!firstA2){
                   8418:           firstA2=1;
                   8419:           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);
                   8420:         }
                   8421:         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  8422:        } /* end bad */
                   8423:      }/* age */
1.266     brouard  8424: 
                   8425:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8426:        sumnewm[cptcod]=0.;
1.266     brouard  8427:        sumnewmr[cptcod]=0.;
1.222     brouard  8428:        for (i=1; i<=nlstate;i++){
                   8429:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8430:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8431:        } 
                   8432:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8433:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8434:           agemingoodr[cptcod]=age;
                   8435:           for (i=1; i<=nlstate;i++)
                   8436:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8437:         }else{ /* bad we change the value with the values of good ages */
                   8438:           for (i=1; i<=nlstate;i++){
                   8439:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8440:           } /* i */
                   8441:         } /* end bad */
                   8442:        }else{
                   8443:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8444:           agemingood[cptcod]=age;
                   8445:         }else{ /* bad */
                   8446:           for (i=1; i<=nlstate;i++){
                   8447:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8448:           } /* i */
                   8449:         } /* end bad */
                   8450:        }/* end else */
                   8451:        sum=0.;sumr=0.;
                   8452:        for (i=1; i<=nlstate;i++){
                   8453:         sum+=mobaverage[(int)age][i][cptcod];
                   8454:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8455:        }
1.266     brouard  8456:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8457:         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  8458:        } /* end bad */
                   8459:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8460:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8461:         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  8462:        } /* end bad */
                   8463:      }/* age */
1.266     brouard  8464: 
1.222     brouard  8465:                
                   8466:      for (age=bage; age<=fage; age++){
1.235     brouard  8467:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8468:        sumnewp[cptcod]=0.;
                   8469:        sumnewm[cptcod]=0.;
                   8470:        for (i=1; i<=nlstate;i++){
                   8471:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8472:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8473:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8474:        }
                   8475:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8476:      }
                   8477:      /* printf("\n"); */
                   8478:      /* } */
1.266     brouard  8479: 
1.222     brouard  8480:      /* brutal averaging */
1.266     brouard  8481:      /* for (i=1; i<=nlstate;i++){ */
                   8482:      /*   for (age=1; age<=bage; age++){ */
                   8483:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8484:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8485:      /*   }     */
                   8486:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8487:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8488:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8489:      /*   } */
                   8490:      /* } /\* end i status *\/ */
                   8491:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8492:      /*   for (age=1; age<=AGESUP; age++){ */
                   8493:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8494:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8495:      /*   } */
                   8496:      /* } */
1.222     brouard  8497:    }/* end cptcod */
1.266     brouard  8498:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8499:    free_vector(agemaxgood,1, ncovcombmax);
                   8500:    free_vector(agemingood,1, ncovcombmax);
                   8501:    free_vector(agemingoodr,1, ncovcombmax);
                   8502:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8503:    free_vector(sumnewm,1, ncovcombmax);
                   8504:    free_vector(sumnewp,1, ncovcombmax);
                   8505:    return 0;
                   8506:  }/* End movingaverage */
1.218     brouard  8507:  
1.126     brouard  8508: 
1.296     brouard  8509:  
1.126     brouard  8510: /************** Forecasting ******************/
1.296     brouard  8511: /* 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)*/
                   8512: 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){
                   8513:   /* dateintemean, mean date of interviews
                   8514:      dateprojd, year, month, day of starting projection 
                   8515:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8516:      agemin, agemax range of age
                   8517:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8518:   */
1.296     brouard  8519:   /* double anprojd, mprojd, jprojd; */
                   8520:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8521:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8522:   double agec; /* generic age */
1.296     brouard  8523:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8524:   double *popeffectif,*popcount;
                   8525:   double ***p3mat;
1.218     brouard  8526:   /* double ***mobaverage; */
1.126     brouard  8527:   char fileresf[FILENAMELENGTH];
                   8528: 
                   8529:   agelim=AGESUP;
1.211     brouard  8530:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8531:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8532:      We still use firstpass and lastpass as another selection.
                   8533:   */
1.214     brouard  8534:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8535:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8536:  
1.201     brouard  8537:   strcpy(fileresf,"F_"); 
                   8538:   strcat(fileresf,fileresu);
1.126     brouard  8539:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8540:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8541:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8542:   }
1.235     brouard  8543:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8544:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8545: 
1.225     brouard  8546:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8547: 
                   8548: 
                   8549:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8550:   if (stepm<=12) stepsize=1;
                   8551:   if(estepm < stepm){
                   8552:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8553:   }
1.270     brouard  8554:   else{
                   8555:     hstepm=estepm;   
                   8556:   }
                   8557:   if(estepm > stepm){ /* Yes every two year */
                   8558:     stepsize=2;
                   8559:   }
1.296     brouard  8560:   hstepm=hstepm/stepm;
1.126     brouard  8561: 
1.296     brouard  8562:   
                   8563:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8564:   /*                              fractional in yp1 *\/ */
                   8565:   /* aintmean=yp; */
                   8566:   /* yp2=modf((yp1*12),&yp); */
                   8567:   /* mintmean=yp; */
                   8568:   /* yp1=modf((yp2*30.5),&yp); */
                   8569:   /* jintmean=yp; */
                   8570:   /* if(jintmean==0) jintmean=1; */
                   8571:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8572: 
1.296     brouard  8573: 
                   8574:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8575:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8576:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8577:   i1=pow(2,cptcoveff);
1.126     brouard  8578:   if (cptcovn < 1){i1=1;}
                   8579:   
1.296     brouard  8580:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8581:   
                   8582:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8583:   
1.126     brouard  8584: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8585:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8586:   for(k=1; k<=i1;k++){
1.253     brouard  8587:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8588:       continue;
1.227     brouard  8589:     if(invalidvarcomb[k]){
                   8590:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8591:       continue;
                   8592:     }
                   8593:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8594:     for(j=1;j<=cptcoveff;j++) {
                   8595:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8596:     }
1.235     brouard  8597:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8598:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8599:     }
1.227     brouard  8600:     fprintf(ficresf," yearproj age");
                   8601:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8602:       for(i=1; i<=nlstate;i++)               
                   8603:        fprintf(ficresf," p%d%d",i,j);
                   8604:       fprintf(ficresf," wp.%d",j);
                   8605:     }
1.296     brouard  8606:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8607:       fprintf(ficresf,"\n");
1.296     brouard  8608:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8609:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8610:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8611:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8612:        nhstepm = nhstepm/hstepm; 
                   8613:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8614:        oldm=oldms;savm=savms;
1.268     brouard  8615:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8616:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8617:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8618:        for (h=0; h<=nhstepm; h++){
                   8619:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8620:            break;
                   8621:          }
                   8622:        }
                   8623:        fprintf(ficresf,"\n");
                   8624:        for(j=1;j<=cptcoveff;j++) 
                   8625:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8626:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8627:        
                   8628:        for(j=1; j<=nlstate+ndeath;j++) {
                   8629:          ppij=0.;
                   8630:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8631:            if (mobilav>=1)
                   8632:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8633:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8634:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8635:            }
1.268     brouard  8636:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8637:          } /* end i */
                   8638:          fprintf(ficresf," %.3f", ppij);
                   8639:        }/* end j */
1.227     brouard  8640:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8641:       } /* end agec */
1.266     brouard  8642:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8643:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8644:     } /* end yearp */
                   8645:   } /* end  k */
1.219     brouard  8646:        
1.126     brouard  8647:   fclose(ficresf);
1.215     brouard  8648:   printf("End of Computing forecasting \n");
                   8649:   fprintf(ficlog,"End of Computing forecasting\n");
                   8650: 
1.126     brouard  8651: }
                   8652: 
1.269     brouard  8653: /************** Back Forecasting ******************/
1.296     brouard  8654:  /* 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){ */
                   8655:  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){
                   8656:   /* back1, year, month, day of starting backprojection
1.267     brouard  8657:      agemin, agemax range of age
                   8658:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8659:      anback2 year of end of backprojection (same day and month as back1).
                   8660:      prevacurrent and prev are prevalences.
1.267     brouard  8661:   */
                   8662:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8663:   double agec; /* generic age */
1.302     brouard  8664:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8665:   double *popeffectif,*popcount;
                   8666:   double ***p3mat;
                   8667:   /* double ***mobaverage; */
                   8668:   char fileresfb[FILENAMELENGTH];
                   8669:  
1.268     brouard  8670:   agelim=AGEINF;
1.267     brouard  8671:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8672:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8673:      We still use firstpass and lastpass as another selection.
                   8674:   */
                   8675:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8676:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8677: 
                   8678:   /*Do we need to compute prevalence again?*/
                   8679: 
                   8680:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8681:   
                   8682:   strcpy(fileresfb,"FB_");
                   8683:   strcat(fileresfb,fileresu);
                   8684:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8685:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8686:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8687:   }
                   8688:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8689:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8690:   
                   8691:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8692:   
                   8693:    
                   8694:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8695:   if (stepm<=12) stepsize=1;
                   8696:   if(estepm < stepm){
                   8697:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8698:   }
1.270     brouard  8699:   else{
                   8700:     hstepm=estepm;   
                   8701:   }
                   8702:   if(estepm >= stepm){ /* Yes every two year */
                   8703:     stepsize=2;
                   8704:   }
1.267     brouard  8705:   
                   8706:   hstepm=hstepm/stepm;
1.296     brouard  8707:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8708:   /*                              fractional in yp1 *\/ */
                   8709:   /* aintmean=yp; */
                   8710:   /* yp2=modf((yp1*12),&yp); */
                   8711:   /* mintmean=yp; */
                   8712:   /* yp1=modf((yp2*30.5),&yp); */
                   8713:   /* jintmean=yp; */
                   8714:   /* if(jintmean==0) jintmean=1; */
                   8715:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8716:   
                   8717:   i1=pow(2,cptcoveff);
                   8718:   if (cptcovn < 1){i1=1;}
                   8719:   
1.296     brouard  8720:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8721:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8722:   
                   8723:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8724:   
                   8725:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8726:   for(k=1; k<=i1;k++){
                   8727:     if(i1 != 1 && TKresult[nres]!= k)
                   8728:       continue;
                   8729:     if(invalidvarcomb[k]){
                   8730:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8731:       continue;
                   8732:     }
1.268     brouard  8733:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8734:     for(j=1;j<=cptcoveff;j++) {
                   8735:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8736:     }
                   8737:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8738:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8739:     }
                   8740:     fprintf(ficresfb," yearbproj age");
                   8741:     for(j=1; j<=nlstate+ndeath;j++){
                   8742:       for(i=1; i<=nlstate;i++)
1.268     brouard  8743:        fprintf(ficresfb," b%d%d",i,j);
                   8744:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8745:     }
1.296     brouard  8746:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8747:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8748:       fprintf(ficresfb,"\n");
1.296     brouard  8749:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8750:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8751:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8752:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8753:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8754:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8755:        nhstepm = nhstepm/hstepm;
                   8756:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8757:        oldm=oldms;savm=savms;
1.268     brouard  8758:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8759:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8760:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8761:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8762:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8763:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8764:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8765:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8766:            break;
                   8767:          }
                   8768:        }
                   8769:        fprintf(ficresfb,"\n");
                   8770:        for(j=1;j<=cptcoveff;j++)
                   8771:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8772:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8773:        for(i=1; i<=nlstate+ndeath;i++) {
                   8774:          ppij=0.;ppi=0.;
                   8775:          for(j=1; j<=nlstate;j++) {
                   8776:            /* if (mobilav==1) */
1.269     brouard  8777:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8778:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8779:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8780:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8781:              /* else { */
                   8782:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8783:              /* } */
1.268     brouard  8784:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8785:          } /* end j */
                   8786:          if(ppi <0.99){
                   8787:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8788:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8789:          }
                   8790:          fprintf(ficresfb," %.3f", ppij);
                   8791:        }/* end j */
1.267     brouard  8792:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8793:       } /* end agec */
                   8794:     } /* end yearp */
                   8795:   } /* end k */
1.217     brouard  8796:   
1.267     brouard  8797:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8798:   
1.267     brouard  8799:   fclose(ficresfb);
                   8800:   printf("End of Computing Back forecasting \n");
                   8801:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8802:        
1.267     brouard  8803: }
1.217     brouard  8804: 
1.269     brouard  8805: /* Variance of prevalence limit: varprlim */
                   8806:  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  8807:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8808:  
                   8809:    char fileresvpl[FILENAMELENGTH];  
                   8810:    FILE *ficresvpl;
                   8811:    double **oldm, **savm;
                   8812:    double **varpl; /* Variances of prevalence limits by age */   
                   8813:    int i1, k, nres, j ;
                   8814:    
                   8815:     strcpy(fileresvpl,"VPL_");
                   8816:     strcat(fileresvpl,fileresu);
                   8817:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8818:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8819:       exit(0);
                   8820:     }
1.288     brouard  8821:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8822:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8823:     
                   8824:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8825:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8826:     
                   8827:     i1=pow(2,cptcoveff);
                   8828:     if (cptcovn < 1){i1=1;}
                   8829: 
                   8830:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8831:     for(k=1; k<=i1;k++){
                   8832:       if(i1 != 1 && TKresult[nres]!= k)
                   8833:        continue;
                   8834:       fprintf(ficresvpl,"\n#****** ");
                   8835:       printf("\n#****** ");
                   8836:       fprintf(ficlog,"\n#****** ");
                   8837:       for(j=1;j<=cptcoveff;j++) {
                   8838:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8839:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8840:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8841:       }
                   8842:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8843:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8844:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8845:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8846:       }        
                   8847:       fprintf(ficresvpl,"******\n");
                   8848:       printf("******\n");
                   8849:       fprintf(ficlog,"******\n");
                   8850:       
                   8851:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8852:       oldm=oldms;savm=savms;
                   8853:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8854:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8855:       /*}*/
                   8856:     }
                   8857:     
                   8858:     fclose(ficresvpl);
1.288     brouard  8859:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8860:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8861: 
                   8862:  }
                   8863: /* Variance of back prevalence: varbprlim */
                   8864:  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){
                   8865:       /*------- Variance of back (stable) prevalence------*/
                   8866: 
                   8867:    char fileresvbl[FILENAMELENGTH];  
                   8868:    FILE  *ficresvbl;
                   8869: 
                   8870:    double **oldm, **savm;
                   8871:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8872:    int i1, k, nres, j ;
                   8873: 
                   8874:    strcpy(fileresvbl,"VBL_");
                   8875:    strcat(fileresvbl,fileresu);
                   8876:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8877:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8878:      exit(0);
                   8879:    }
                   8880:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8881:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8882:    
                   8883:    
                   8884:    i1=pow(2,cptcoveff);
                   8885:    if (cptcovn < 1){i1=1;}
                   8886:    
                   8887:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8888:      for(k=1; k<=i1;k++){
                   8889:        if(i1 != 1 && TKresult[nres]!= k)
                   8890:         continue;
                   8891:        fprintf(ficresvbl,"\n#****** ");
                   8892:        printf("\n#****** ");
                   8893:        fprintf(ficlog,"\n#****** ");
                   8894:        for(j=1;j<=cptcoveff;j++) {
                   8895:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8896:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8897:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8898:        }
                   8899:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8900:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8901:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8902:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8903:        }
                   8904:        fprintf(ficresvbl,"******\n");
                   8905:        printf("******\n");
                   8906:        fprintf(ficlog,"******\n");
                   8907:        
                   8908:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8909:        oldm=oldms;savm=savms;
                   8910:        
                   8911:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8912:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8913:        /*}*/
                   8914:      }
                   8915:    
                   8916:    fclose(ficresvbl);
                   8917:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8918:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8919: 
                   8920:  } /* End of varbprlim */
                   8921: 
1.126     brouard  8922: /************** Forecasting *****not tested NB*************/
1.227     brouard  8923: /* 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  8924:   
1.227     brouard  8925: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8926: /*   int *popage; */
                   8927: /*   double calagedatem, agelim, kk1, kk2; */
                   8928: /*   double *popeffectif,*popcount; */
                   8929: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8930: /*   /\* double ***mobaverage; *\/ */
                   8931: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8932: 
1.227     brouard  8933: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8934: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8935: /*   agelim=AGESUP; */
                   8936: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8937:   
1.227     brouard  8938: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8939:   
                   8940:   
1.227     brouard  8941: /*   strcpy(filerespop,"POP_");  */
                   8942: /*   strcat(filerespop,fileresu); */
                   8943: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8944: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8945: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8946: /*   } */
                   8947: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8948: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8949: 
1.227     brouard  8950: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8951: 
1.227     brouard  8952: /*   /\* if (mobilav!=0) { *\/ */
                   8953: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8954: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8955: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8956: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8957: /*   /\*   } *\/ */
                   8958: /*   /\* } *\/ */
1.126     brouard  8959: 
1.227     brouard  8960: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8961: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8962:   
1.227     brouard  8963: /*   agelim=AGESUP; */
1.126     brouard  8964:   
1.227     brouard  8965: /*   hstepm=1; */
                   8966: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8967:        
1.227     brouard  8968: /*   if (popforecast==1) { */
                   8969: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8970: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8971: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8972: /*     }  */
                   8973: /*     popage=ivector(0,AGESUP); */
                   8974: /*     popeffectif=vector(0,AGESUP); */
                   8975: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8976:     
1.227     brouard  8977: /*     i=1;    */
                   8978: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8979:     
1.227     brouard  8980: /*     imx=i; */
                   8981: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8982: /*   } */
1.218     brouard  8983:   
1.227     brouard  8984: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8985: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8986: /*       k=k+1; */
                   8987: /*       fprintf(ficrespop,"\n#******"); */
                   8988: /*       for(j=1;j<=cptcoveff;j++) { */
                   8989: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8990: /*       } */
                   8991: /*       fprintf(ficrespop,"******\n"); */
                   8992: /*       fprintf(ficrespop,"# Age"); */
                   8993: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8994: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8995:       
1.227     brouard  8996: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8997: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8998:        
1.227     brouard  8999: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9000: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9001: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9002:          
1.227     brouard  9003: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9004: /*       oldm=oldms;savm=savms; */
                   9005: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9006:          
1.227     brouard  9007: /*       for (h=0; h<=nhstepm; h++){ */
                   9008: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9009: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9010: /*         }  */
                   9011: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9012: /*           kk1=0.;kk2=0; */
                   9013: /*           for(i=1; i<=nlstate;i++) {               */
                   9014: /*             if (mobilav==1)  */
                   9015: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9016: /*             else { */
                   9017: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9018: /*             } */
                   9019: /*           } */
                   9020: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9021: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9022: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9023: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9024: /*           } */
                   9025: /*         } */
                   9026: /*         for(i=1; i<=nlstate;i++){ */
                   9027: /*           kk1=0.; */
                   9028: /*           for(j=1; j<=nlstate;j++){ */
                   9029: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9030: /*           } */
                   9031: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9032: /*         } */
1.218     brouard  9033:            
1.227     brouard  9034: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9035: /*           for(j=1; j<=nlstate;j++)  */
                   9036: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9037: /*       } */
                   9038: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9039: /*     } */
                   9040: /*       } */
1.218     brouard  9041:       
1.227     brouard  9042: /*       /\******\/ */
1.218     brouard  9043:       
1.227     brouard  9044: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9045: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9046: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9047: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9048: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9049:          
1.227     brouard  9050: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9051: /*       oldm=oldms;savm=savms; */
                   9052: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9053: /*       for (h=0; h<=nhstepm; h++){ */
                   9054: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9055: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9056: /*         }  */
                   9057: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9058: /*           kk1=0.;kk2=0; */
                   9059: /*           for(i=1; i<=nlstate;i++) {               */
                   9060: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9061: /*           } */
                   9062: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9063: /*         } */
                   9064: /*       } */
                   9065: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9066: /*     } */
                   9067: /*       } */
                   9068: /*     }  */
                   9069: /*   } */
1.218     brouard  9070:   
1.227     brouard  9071: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9072:   
1.227     brouard  9073: /*   if (popforecast==1) { */
                   9074: /*     free_ivector(popage,0,AGESUP); */
                   9075: /*     free_vector(popeffectif,0,AGESUP); */
                   9076: /*     free_vector(popcount,0,AGESUP); */
                   9077: /*   } */
                   9078: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9079: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9080: /*   fclose(ficrespop); */
                   9081: /* } /\* End of popforecast *\/ */
1.218     brouard  9082:  
1.126     brouard  9083: int fileappend(FILE *fichier, char *optionfich)
                   9084: {
                   9085:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9086:     printf("Problem with file: %s\n", optionfich);
                   9087:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9088:     return (0);
                   9089:   }
                   9090:   fflush(fichier);
                   9091:   return (1);
                   9092: }
                   9093: 
                   9094: 
                   9095: /**************** function prwizard **********************/
                   9096: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9097: {
                   9098: 
                   9099:   /* Wizard to print covariance matrix template */
                   9100: 
1.164     brouard  9101:   char ca[32], cb[32];
                   9102:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9103:   int numlinepar;
                   9104: 
                   9105:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9106:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9107:   for(i=1; i <=nlstate; i++){
                   9108:     jj=0;
                   9109:     for(j=1; j <=nlstate+ndeath; j++){
                   9110:       if(j==i) continue;
                   9111:       jj++;
                   9112:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9113:       printf("%1d%1d",i,j);
                   9114:       fprintf(ficparo,"%1d%1d",i,j);
                   9115:       for(k=1; k<=ncovmodel;k++){
                   9116:        /*        printf(" %lf",param[i][j][k]); */
                   9117:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9118:        printf(" 0.");
                   9119:        fprintf(ficparo," 0.");
                   9120:       }
                   9121:       printf("\n");
                   9122:       fprintf(ficparo,"\n");
                   9123:     }
                   9124:   }
                   9125:   printf("# Scales (for hessian or gradient estimation)\n");
                   9126:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9127:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9128:   for(i=1; i <=nlstate; i++){
                   9129:     jj=0;
                   9130:     for(j=1; j <=nlstate+ndeath; j++){
                   9131:       if(j==i) continue;
                   9132:       jj++;
                   9133:       fprintf(ficparo,"%1d%1d",i,j);
                   9134:       printf("%1d%1d",i,j);
                   9135:       fflush(stdout);
                   9136:       for(k=1; k<=ncovmodel;k++){
                   9137:        /*      printf(" %le",delti3[i][j][k]); */
                   9138:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9139:        printf(" 0.");
                   9140:        fprintf(ficparo," 0.");
                   9141:       }
                   9142:       numlinepar++;
                   9143:       printf("\n");
                   9144:       fprintf(ficparo,"\n");
                   9145:     }
                   9146:   }
                   9147:   printf("# Covariance matrix\n");
                   9148: /* # 121 Var(a12)\n\ */
                   9149: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9150: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9151: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9152: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9153: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9154: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9155: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9156:   fflush(stdout);
                   9157:   fprintf(ficparo,"# Covariance matrix\n");
                   9158:   /* # 121 Var(a12)\n\ */
                   9159:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9160:   /* #   ...\n\ */
                   9161:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9162:   
                   9163:   for(itimes=1;itimes<=2;itimes++){
                   9164:     jj=0;
                   9165:     for(i=1; i <=nlstate; i++){
                   9166:       for(j=1; j <=nlstate+ndeath; j++){
                   9167:        if(j==i) continue;
                   9168:        for(k=1; k<=ncovmodel;k++){
                   9169:          jj++;
                   9170:          ca[0]= k+'a'-1;ca[1]='\0';
                   9171:          if(itimes==1){
                   9172:            printf("#%1d%1d%d",i,j,k);
                   9173:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9174:          }else{
                   9175:            printf("%1d%1d%d",i,j,k);
                   9176:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9177:            /*  printf(" %.5le",matcov[i][j]); */
                   9178:          }
                   9179:          ll=0;
                   9180:          for(li=1;li <=nlstate; li++){
                   9181:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9182:              if(lj==li) continue;
                   9183:              for(lk=1;lk<=ncovmodel;lk++){
                   9184:                ll++;
                   9185:                if(ll<=jj){
                   9186:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9187:                  if(ll<jj){
                   9188:                    if(itimes==1){
                   9189:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9190:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9191:                    }else{
                   9192:                      printf(" 0.");
                   9193:                      fprintf(ficparo," 0.");
                   9194:                    }
                   9195:                  }else{
                   9196:                    if(itimes==1){
                   9197:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9198:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9199:                    }else{
                   9200:                      printf(" 0.");
                   9201:                      fprintf(ficparo," 0.");
                   9202:                    }
                   9203:                  }
                   9204:                }
                   9205:              } /* end lk */
                   9206:            } /* end lj */
                   9207:          } /* end li */
                   9208:          printf("\n");
                   9209:          fprintf(ficparo,"\n");
                   9210:          numlinepar++;
                   9211:        } /* end k*/
                   9212:       } /*end j */
                   9213:     } /* end i */
                   9214:   } /* end itimes */
                   9215: 
                   9216: } /* end of prwizard */
                   9217: /******************* Gompertz Likelihood ******************************/
                   9218: double gompertz(double x[])
                   9219: { 
1.302     brouard  9220:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9221:   int i,n=0; /* n is the size of the sample */
                   9222: 
1.220     brouard  9223:   for (i=1;i<=imx ; i++) {
1.126     brouard  9224:     sump=sump+weight[i];
                   9225:     /*    sump=sump+1;*/
                   9226:     num=num+1;
                   9227:   }
1.302     brouard  9228:   L=0.0;
                   9229:   /* agegomp=AGEGOMP; */
1.126     brouard  9230:   /* for (i=0; i<=imx; i++) 
                   9231:      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]);*/
                   9232: 
1.302     brouard  9233:   for (i=1;i<=imx ; i++) {
                   9234:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9235:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9236:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9237:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9238:      * +
                   9239:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9240:      */
                   9241:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9242:        if (cens[i] == 1){
                   9243:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9244:        } else if (cens[i] == 0){
1.126     brouard  9245:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9246:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9247:       } else
                   9248:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9249:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9250:        L=L+A*weight[i];
1.126     brouard  9251:        /*      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  9252:      }
                   9253:   }
1.126     brouard  9254: 
1.302     brouard  9255:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9256:  
                   9257:   return -2*L*num/sump;
                   9258: }
                   9259: 
1.136     brouard  9260: #ifdef GSL
                   9261: /******************* Gompertz_f Likelihood ******************************/
                   9262: double gompertz_f(const gsl_vector *v, void *params)
                   9263: { 
1.302     brouard  9264:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9265:   double *x= (double *) v->data;
                   9266:   int i,n=0; /* n is the size of the sample */
                   9267: 
                   9268:   for (i=0;i<=imx-1 ; i++) {
                   9269:     sump=sump+weight[i];
                   9270:     /*    sump=sump+1;*/
                   9271:     num=num+1;
                   9272:   }
                   9273:  
                   9274:  
                   9275:   /* for (i=0; i<=imx; i++) 
                   9276:      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]);*/
                   9277:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9278:   for (i=1;i<=imx ; i++)
                   9279:     {
                   9280:       if (cens[i] == 1 && wav[i]>1)
                   9281:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9282:       
                   9283:       if (cens[i] == 0 && wav[i]>1)
                   9284:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9285:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9286:       
                   9287:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9288:       if (wav[i] > 1 ) { /* ??? */
                   9289:        LL=LL+A*weight[i];
                   9290:        /*      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]);*/
                   9291:       }
                   9292:     }
                   9293: 
                   9294:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9295:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9296:  
                   9297:   return -2*LL*num/sump;
                   9298: }
                   9299: #endif
                   9300: 
1.126     brouard  9301: /******************* Printing html file ***********/
1.201     brouard  9302: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9303:                  int lastpass, int stepm, int weightopt, char model[],\
                   9304:                  int imx,  double p[],double **matcov,double agemortsup){
                   9305:   int i,k;
                   9306: 
                   9307:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9308:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9309:   for (i=1;i<=2;i++) 
                   9310:     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  9311:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9312:   fprintf(fichtm,"</ul>");
                   9313: 
                   9314: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9315: 
                   9316:  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>");
                   9317: 
                   9318:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9319:    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]);
                   9320: 
                   9321:  
                   9322:   fflush(fichtm);
                   9323: }
                   9324: 
                   9325: /******************* Gnuplot file **************/
1.201     brouard  9326: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9327: 
                   9328:   char dirfileres[132],optfileres[132];
1.164     brouard  9329: 
1.126     brouard  9330:   int ng;
                   9331: 
                   9332: 
                   9333:   /*#ifdef windows */
                   9334:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9335:     /*#endif */
                   9336: 
                   9337: 
                   9338:   strcpy(dirfileres,optionfilefiname);
                   9339:   strcpy(optfileres,"vpl");
1.199     brouard  9340:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9341:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9342:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9343:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9344:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9345: 
                   9346: } 
                   9347: 
1.136     brouard  9348: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9349: {
1.126     brouard  9350: 
1.136     brouard  9351:   /*-------- data file ----------*/
                   9352:   FILE *fic;
                   9353:   char dummy[]="                         ";
1.240     brouard  9354:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9355:   int lstra;
1.136     brouard  9356:   int linei, month, year,iout;
1.302     brouard  9357:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9358:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9359:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9360:   char *stratrunc;
1.223     brouard  9361: 
1.240     brouard  9362:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9363:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9364: 
1.240     brouard  9365:   for(v=1; v <=ncovcol;v++){
                   9366:     DummyV[v]=0;
                   9367:     FixedV[v]=0;
                   9368:   }
                   9369:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9370:     DummyV[v]=1;
                   9371:     FixedV[v]=0;
                   9372:   }
                   9373:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9374:     DummyV[v]=0;
                   9375:     FixedV[v]=1;
                   9376:   }
                   9377:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9378:     DummyV[v]=1;
                   9379:     FixedV[v]=1;
                   9380:   }
                   9381:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9382:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9383:     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]);
                   9384:   }
1.126     brouard  9385: 
1.136     brouard  9386:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9387:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9388:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9389:   }
1.126     brouard  9390: 
1.302     brouard  9391:     /* Is it a BOM UTF-8 Windows file? */
                   9392:   /* First data line */
                   9393:   linei=0;
                   9394:   while(fgets(line, MAXLINE, fic)) {
                   9395:     noffset=0;
                   9396:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9397:     {
                   9398:       noffset=noffset+3;
                   9399:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9400:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9401:       fflush(ficlog); return 1;
                   9402:     }
                   9403:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9404:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9405:     {
                   9406:       noffset=noffset+2;
1.304     brouard  9407:       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);
                   9408:       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  9409:       fflush(ficlog); return 1;
                   9410:     }
                   9411:     else if( line[0] == 0 && line[1] == 0)
                   9412:     {
                   9413:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9414:        noffset=noffset+4;
1.304     brouard  9415:        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);
                   9416:        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  9417:        fflush(ficlog); return 1;
                   9418:       }
                   9419:     } else{
                   9420:       ;/*printf(" Not a BOM file\n");*/
                   9421:     }
                   9422:         /* If line starts with a # it is a comment */
                   9423:     if (line[noffset] == '#') {
                   9424:       linei=linei+1;
                   9425:       break;
                   9426:     }else{
                   9427:       break;
                   9428:     }
                   9429:   }
                   9430:   fclose(fic);
                   9431:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9432:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9433:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9434:   }
                   9435:   /* Not a Bom file */
                   9436:   
1.136     brouard  9437:   i=1;
                   9438:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9439:     linei=linei+1;
                   9440:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9441:       if(line[j] == '\t')
                   9442:        line[j] = ' ';
                   9443:     }
                   9444:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9445:       ;
                   9446:     };
                   9447:     line[j+1]=0;  /* Trims blanks at end of line */
                   9448:     if(line[0]=='#'){
                   9449:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9450:       printf("Comment line\n%s\n",line);
                   9451:       continue;
                   9452:     }
                   9453:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9454:     strcpy(line, linetmp);
1.223     brouard  9455:     
                   9456:     /* Loops on waves */
                   9457:     for (j=maxwav;j>=1;j--){
                   9458:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9459:        cutv(stra, strb, line, ' '); 
                   9460:        if(strb[0]=='.') { /* Missing value */
                   9461:          lval=-1;
                   9462:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9463:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9464:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9465:            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);
                   9466:            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);
                   9467:            return 1;
                   9468:          }
                   9469:        }else{
                   9470:          errno=0;
                   9471:          /* what_kind_of_number(strb); */
                   9472:          dval=strtod(strb,&endptr); 
                   9473:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9474:          /* if(strb != endptr && *endptr == '\0') */
                   9475:          /*    dval=dlval; */
                   9476:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9477:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9478:            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);
                   9479:            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);
                   9480:            return 1;
                   9481:          }
                   9482:          cotqvar[j][iv][i]=dval; 
                   9483:          cotvar[j][ntv+iv][i]=dval; 
                   9484:        }
                   9485:        strcpy(line,stra);
1.223     brouard  9486:       }/* end loop ntqv */
1.225     brouard  9487:       
1.223     brouard  9488:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9489:        cutv(stra, strb, line, ' '); 
                   9490:        if(strb[0]=='.') { /* Missing value */
                   9491:          lval=-1;
                   9492:        }else{
                   9493:          errno=0;
                   9494:          lval=strtol(strb,&endptr,10); 
                   9495:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9496:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9497:            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);
                   9498:            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);
                   9499:            return 1;
                   9500:          }
                   9501:        }
                   9502:        if(lval <-1 || lval >1){
                   9503:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9504:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9505:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9506:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9507:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9508:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9509:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9510:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9511:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9512:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9513:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9514:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9515:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9516:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9517:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9518:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9519:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9520:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9521:          return 1;
                   9522:        }
                   9523:        cotvar[j][iv][i]=(double)(lval);
                   9524:        strcpy(line,stra);
1.223     brouard  9525:       }/* end loop ntv */
1.225     brouard  9526:       
1.223     brouard  9527:       /* Statuses  at wave */
1.137     brouard  9528:       cutv(stra, strb, line, ' '); 
1.223     brouard  9529:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9530:        lval=-1;
1.136     brouard  9531:       }else{
1.238     brouard  9532:        errno=0;
                   9533:        lval=strtol(strb,&endptr,10); 
                   9534:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9535:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9536:          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);
                   9537:          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);
                   9538:          return 1;
                   9539:        }
1.136     brouard  9540:       }
1.225     brouard  9541:       
1.136     brouard  9542:       s[j][i]=lval;
1.225     brouard  9543:       
1.223     brouard  9544:       /* Date of Interview */
1.136     brouard  9545:       strcpy(line,stra);
                   9546:       cutv(stra, strb,line,' ');
1.169     brouard  9547:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9548:       }
1.169     brouard  9549:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9550:        month=99;
                   9551:        year=9999;
1.136     brouard  9552:       }else{
1.225     brouard  9553:        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);
                   9554:        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);
                   9555:        return 1;
1.136     brouard  9556:       }
                   9557:       anint[j][i]= (double) year; 
1.302     brouard  9558:       mint[j][i]= (double)month;
                   9559:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9560:       /*       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]); */
                   9561:       /*       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]); */
                   9562:       /* } */
1.136     brouard  9563:       strcpy(line,stra);
1.223     brouard  9564:     } /* End loop on waves */
1.225     brouard  9565:     
1.223     brouard  9566:     /* Date of death */
1.136     brouard  9567:     cutv(stra, strb,line,' '); 
1.169     brouard  9568:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9569:     }
1.169     brouard  9570:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9571:       month=99;
                   9572:       year=9999;
                   9573:     }else{
1.141     brouard  9574:       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  9575:       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);
                   9576:       return 1;
1.136     brouard  9577:     }
                   9578:     andc[i]=(double) year; 
                   9579:     moisdc[i]=(double) month; 
                   9580:     strcpy(line,stra);
                   9581:     
1.223     brouard  9582:     /* Date of birth */
1.136     brouard  9583:     cutv(stra, strb,line,' '); 
1.169     brouard  9584:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9585:     }
1.169     brouard  9586:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9587:       month=99;
                   9588:       year=9999;
                   9589:     }else{
1.141     brouard  9590:       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);
                   9591:       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  9592:       return 1;
1.136     brouard  9593:     }
                   9594:     if (year==9999) {
1.141     brouard  9595:       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);
                   9596:       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  9597:       return 1;
                   9598:       
1.136     brouard  9599:     }
                   9600:     annais[i]=(double)(year);
1.302     brouard  9601:     moisnais[i]=(double)(month);
                   9602:     for (j=1;j<=maxwav;j++){
                   9603:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9604:        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]);
                   9605:        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]);
                   9606:       }
                   9607:     }
                   9608: 
1.136     brouard  9609:     strcpy(line,stra);
1.225     brouard  9610:     
1.223     brouard  9611:     /* Sample weight */
1.136     brouard  9612:     cutv(stra, strb,line,' '); 
                   9613:     errno=0;
                   9614:     dval=strtod(strb,&endptr); 
                   9615:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9616:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9617:       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  9618:       fflush(ficlog);
                   9619:       return 1;
                   9620:     }
                   9621:     weight[i]=dval; 
                   9622:     strcpy(line,stra);
1.225     brouard  9623:     
1.223     brouard  9624:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9625:       cutv(stra, strb, line, ' '); 
                   9626:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9627:        lval=-1;
1.311     brouard  9628:        coqvar[iv][i]=NAN; 
                   9629:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9630:       }else{
1.225     brouard  9631:        errno=0;
                   9632:        /* what_kind_of_number(strb); */
                   9633:        dval=strtod(strb,&endptr);
                   9634:        /* if(strb != endptr && *endptr == '\0') */
                   9635:        /*   dval=dlval; */
                   9636:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9637:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9638:          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);
                   9639:          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);
                   9640:          return 1;
                   9641:        }
                   9642:        coqvar[iv][i]=dval; 
1.226     brouard  9643:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9644:       }
                   9645:       strcpy(line,stra);
                   9646:     }/* end loop nqv */
1.136     brouard  9647:     
1.223     brouard  9648:     /* Covariate values */
1.136     brouard  9649:     for (j=ncovcol;j>=1;j--){
                   9650:       cutv(stra, strb,line,' '); 
1.223     brouard  9651:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9652:        lval=-1;
1.136     brouard  9653:       }else{
1.225     brouard  9654:        errno=0;
                   9655:        lval=strtol(strb,&endptr,10); 
                   9656:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9657:          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);
                   9658:          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);
                   9659:          return 1;
                   9660:        }
1.136     brouard  9661:       }
                   9662:       if(lval <-1 || lval >1){
1.225     brouard  9663:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9664:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9665:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9666:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9667:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9668:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9669:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9670:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9671:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9672:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9673:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9674:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9675:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9676:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9677:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9678:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9679:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9680:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9681:        return 1;
1.136     brouard  9682:       }
                   9683:       covar[j][i]=(double)(lval);
                   9684:       strcpy(line,stra);
                   9685:     }  
                   9686:     lstra=strlen(stra);
1.225     brouard  9687:     
1.136     brouard  9688:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9689:       stratrunc = &(stra[lstra-9]);
                   9690:       num[i]=atol(stratrunc);
                   9691:     }
                   9692:     else
                   9693:       num[i]=atol(stra);
                   9694:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9695:       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;}*/
                   9696:     
                   9697:     i=i+1;
                   9698:   } /* End loop reading  data */
1.225     brouard  9699:   
1.136     brouard  9700:   *imax=i-1; /* Number of individuals */
                   9701:   fclose(fic);
1.225     brouard  9702:   
1.136     brouard  9703:   return (0);
1.164     brouard  9704:   /* endread: */
1.225     brouard  9705:   printf("Exiting readdata: ");
                   9706:   fclose(fic);
                   9707:   return (1);
1.223     brouard  9708: }
1.126     brouard  9709: 
1.234     brouard  9710: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9711:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9712:   while (*p2 == ' ')
1.234     brouard  9713:     p2++; 
                   9714:   /* while ((*p1++ = *p2++) !=0) */
                   9715:   /*   ; */
                   9716:   /* do */
                   9717:   /*   while (*p2 == ' ') */
                   9718:   /*     p2++; */
                   9719:   /* while (*p1++ == *p2++); */
                   9720:   *stri=p2; 
1.145     brouard  9721: }
                   9722: 
1.235     brouard  9723: int decoderesult ( char resultline[], int nres)
1.230     brouard  9724: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9725: {
1.235     brouard  9726:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9727:   char resultsav[MAXLINE];
1.234     brouard  9728:   int resultmodel[MAXLINE];
                   9729:   int modelresult[MAXLINE];
1.230     brouard  9730:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9731: 
1.234     brouard  9732:   removefirstspace(&resultline);
1.230     brouard  9733: 
                   9734:   if (strstr(resultline,"v") !=0){
                   9735:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9736:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9737:     return 1;
                   9738:   }
                   9739:   trimbb(resultsav, resultline);
                   9740:   if (strlen(resultsav) >1){
                   9741:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9742:   }
1.253     brouard  9743:   if(j == 0){ /* Resultline but no = */
                   9744:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9745:     return (0);
                   9746:   }
1.234     brouard  9747:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.310     brouard  9748:     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);
                   9749:     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  9750:   }
                   9751:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9752:     if(nbocc(resultsav,'=') >1){
                   9753:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
1.310     brouard  9754:                                      resultsav= V4=1 V5=25.1 V3=0 stra= V5=25.1 V3=0 strb= V4=1 */
1.234     brouard  9755:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9756:     }else
                   9757:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9758:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9759:     
1.230     brouard  9760:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9761:     Tvarsel[k]=atoi(strc);
                   9762:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9763:     /* cptcovsel++;     */
                   9764:     if (nbocc(stra,'=') >0)
                   9765:       strcpy(resultsav,stra); /* and analyzes it */
                   9766:   }
1.235     brouard  9767:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9768:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9769:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9770:       match=0;
1.236     brouard  9771:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9772:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9773:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9774:          match=1;
                   9775:          break;
                   9776:        }
                   9777:       }
                   9778:       if(match == 0){
1.310     brouard  9779:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9780:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9781:        return 1;
1.234     brouard  9782:       }
                   9783:     }
                   9784:   }
1.235     brouard  9785:   /* Checking for missing or useless values in comparison of current model needs */
                   9786:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9787:     match=0;
1.235     brouard  9788:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9789:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9790:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9791:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9792:          ++match;
                   9793:        }
                   9794:       }
                   9795:     }
                   9796:     if(match == 0){
                   9797:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310     brouard  9798:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9799:       return 1;
1.234     brouard  9800:     }else if(match > 1){
                   9801:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  9802:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9803:       return 1;
1.234     brouard  9804:     }
                   9805:   }
1.235     brouard  9806:       
1.234     brouard  9807:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9808:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9809:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9810:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9811:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9812:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9813:   /*    1 0 0 0 */
                   9814:   /*    2 1 0 0 */
                   9815:   /*    3 0 1 0 */ 
                   9816:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9817:   /*    5 0 0 1 */
                   9818:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9819:   /*    7 0 1 1 */
                   9820:   /*    8 1 1 1 */
1.237     brouard  9821:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9822:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9823:   /* V5*age V5 known which value for nres?  */
                   9824:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9825:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9826:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9827:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9828:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9829:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9830:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9831:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9832:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9833:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9834:       k4++;;
                   9835:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9836:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9837:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9838:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9839:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9840:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9841:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9842:       k4q++;;
                   9843:     }
                   9844:   }
1.234     brouard  9845:   
1.235     brouard  9846:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9847:   return (0);
                   9848: }
1.235     brouard  9849: 
1.230     brouard  9850: int decodemodel( char model[], int lastobs)
                   9851:  /**< This routine decodes the model and returns:
1.224     brouard  9852:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9853:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9854:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9855:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9856:        * - cptcovage number of covariates with age*products =2
                   9857:        * - cptcovs number of simple covariates
                   9858:        * - 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
                   9859:        *     which is a new column after the 9 (ncovcol) variables. 
                   9860:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9861:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9862:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9863:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9864:        */
1.136     brouard  9865: {
1.238     brouard  9866:   int i, j, k, ks, v;
1.227     brouard  9867:   int  j1, k1, k2, k3, k4;
1.136     brouard  9868:   char modelsav[80];
1.145     brouard  9869:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9870:   char *strpt;
1.136     brouard  9871: 
1.145     brouard  9872:   /*removespace(model);*/
1.136     brouard  9873:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9874:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9875:     if (strstr(model,"AGE") !=0){
1.192     brouard  9876:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9877:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9878:       return 1;
                   9879:     }
1.141     brouard  9880:     if (strstr(model,"v") !=0){
                   9881:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9882:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9883:       return 1;
                   9884:     }
1.187     brouard  9885:     strcpy(modelsav,model); 
                   9886:     if ((strpt=strstr(model,"age*age")) !=0){
                   9887:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9888:       if(strpt != model){
1.234     brouard  9889:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9890:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9891:  corresponding column of parameters.\n",model);
1.234     brouard  9892:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9893:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9894:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9895:        return 1;
1.225     brouard  9896:       }
1.187     brouard  9897:       nagesqr=1;
                   9898:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9899:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9900:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9901:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9902:       else 
1.234     brouard  9903:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9904:     }else
                   9905:       nagesqr=0;
                   9906:     if (strlen(modelsav) >1){
                   9907:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9908:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9909:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9910:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9911:                     * cst, age and age*age 
                   9912:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9913:       /* including age products which are counted in cptcovage.
                   9914:        * but the covariates which are products must be treated 
                   9915:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9916:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9917:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9918:       
                   9919:       
1.187     brouard  9920:       /*   Design
                   9921:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9922:        *  <          ncovcol=8                >
                   9923:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9924:        *   k=  1    2      3       4     5       6      7        8
                   9925:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9926:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9927:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9928:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9929:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9930:        *  Tage[++cptcovage]=k
                   9931:        *       if products, new covar are created after ncovcol with k1
                   9932:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9933:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9934:        *  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
                   9935:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9936:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9937:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9938:        *  <          ncovcol=8                >
                   9939:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9940:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9941:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9942:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9943:        * p Tprod[1]@2={                         6, 5}
                   9944:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9945:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9946:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9947:        *How to reorganize?
                   9948:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9949:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9950:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9951:        * Struct []
                   9952:        */
1.225     brouard  9953:       
1.187     brouard  9954:       /* This loop fills the array Tvar from the string 'model'.*/
                   9955:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9956:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9957:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9958:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9959:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9960:       /*       k=1 Tvar[1]=2 (from V2) */
                   9961:       /*       k=5 Tvar[5] */
                   9962:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9963:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9964:       /*       } */
1.198     brouard  9965:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9966:       /*
                   9967:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9968:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9969:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9970:       }
1.187     brouard  9971:       cptcovage=0;
                   9972:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9973:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9974:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9975:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9976:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9977:        /*scanf("%d",i);*/
                   9978:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9979:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9980:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9981:            /* covar is not filled and then is empty */
                   9982:            cptcovprod--;
                   9983:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9984:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9985:            Typevar[k]=1;  /* 1 for age product */
                   9986:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9987:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9988:            /*printf("stre=%s ", stre);*/
                   9989:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9990:            cptcovprod--;
                   9991:            cutl(stre,strb,strc,'V');
                   9992:            Tvar[k]=atoi(stre);
                   9993:            Typevar[k]=1;  /* 1 for age product */
                   9994:            cptcovage++;
                   9995:            Tage[cptcovage]=k;
                   9996:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9997:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9998:            cptcovn++;
                   9999:            cptcovprodnoage++;k1++;
                   10000:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10001:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10002:                                                because this model-covariate is a construction we invent a new column
                   10003:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   10004:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   10005:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   10006:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10007:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10008:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   10009:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   10010:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   10011:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   10012:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10013:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10014:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10015:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10016:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10017:            for (i=1; i<=lastobs;i++){
                   10018:              /* Computes the new covariate which is a product of
                   10019:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10020:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10021:            }
                   10022:          } /* End age is not in the model */
                   10023:        } /* End if model includes a product */
                   10024:        else { /* no more sum */
                   10025:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10026:          /*  scanf("%d",i);*/
                   10027:          cutl(strd,strc,strb,'V');
                   10028:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10029:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10030:          Tvar[k]=atoi(strd);
                   10031:          Typevar[k]=0;  /* 0 for simple covariates */
                   10032:        }
                   10033:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10034:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10035:                                  scanf("%d",i);*/
1.187     brouard  10036:       } /* end of loop + on total covariates */
                   10037:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10038:   } /* end if strlen(model == 0) */
1.136     brouard  10039:   
                   10040:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10041:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10042:   
1.136     brouard  10043:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10044:      printf("cptcovprod=%d ", cptcovprod);
                   10045:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10046:      scanf("%d ",i);*/
                   10047: 
                   10048: 
1.230     brouard  10049: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10050:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10051: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10052:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10053:    k =           1    2   3     4       5       6      7      8        9
                   10054:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   10055:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  10056:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10057:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10058:          Tmodelind[combination of covar]=k;
1.225     brouard  10059: */  
                   10060: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10061:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10062:   /* 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  10063:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  10064:   printf("Model=%s\n\
                   10065: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10066: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10067: 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);
                   10068:   fprintf(ficlog,"Model=%s\n\
                   10069: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10070: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10071: 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  10072:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10073:   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 */
                   10074:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10075:       Fixed[k]= 0;
                   10076:       Dummy[k]= 0;
1.225     brouard  10077:       ncoveff++;
1.232     brouard  10078:       ncovf++;
1.234     brouard  10079:       nsd++;
                   10080:       modell[k].maintype= FTYPE;
                   10081:       TvarsD[nsd]=Tvar[k];
                   10082:       TvarsDind[nsd]=k;
                   10083:       TvarF[ncovf]=Tvar[k];
                   10084:       TvarFind[ncovf]=k;
                   10085:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10086:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10087:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10088:       Fixed[k]= 0;
                   10089:       Dummy[k]= 0;
                   10090:       ncoveff++;
                   10091:       ncovf++;
                   10092:       modell[k].maintype= FTYPE;
                   10093:       TvarF[ncovf]=Tvar[k];
                   10094:       TvarFind[ncovf]=k;
1.230     brouard  10095:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10096:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10097:     }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  10098:       Fixed[k]= 0;
                   10099:       Dummy[k]= 1;
1.230     brouard  10100:       nqfveff++;
1.234     brouard  10101:       modell[k].maintype= FTYPE;
                   10102:       modell[k].subtype= FQ;
                   10103:       nsq++;
                   10104:       TvarsQ[nsq]=Tvar[k];
                   10105:       TvarsQind[nsq]=k;
1.232     brouard  10106:       ncovf++;
1.234     brouard  10107:       TvarF[ncovf]=Tvar[k];
                   10108:       TvarFind[ncovf]=k;
1.231     brouard  10109:       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  10110:       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  10111:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10112:       Fixed[k]= 1;
                   10113:       Dummy[k]= 0;
1.225     brouard  10114:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10115:       modell[k].maintype= VTYPE;
                   10116:       modell[k].subtype= VD;
                   10117:       nsd++;
                   10118:       TvarsD[nsd]=Tvar[k];
                   10119:       TvarsDind[nsd]=k;
                   10120:       ncovv++; /* Only simple time varying variables */
                   10121:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10122:       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  10123:       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 */
                   10124:       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  10125:       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);
                   10126:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10127:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10128:       Fixed[k]= 1;
                   10129:       Dummy[k]= 1;
                   10130:       nqtveff++;
                   10131:       modell[k].maintype= VTYPE;
                   10132:       modell[k].subtype= VQ;
                   10133:       ncovv++; /* Only simple time varying variables */
                   10134:       nsq++;
                   10135:       TvarsQ[nsq]=Tvar[k];
                   10136:       TvarsQind[nsq]=k;
                   10137:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10138:       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  10139:       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 */
                   10140:       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  10141:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10142:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10143:       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  10144:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10145:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10146:       ncova++;
                   10147:       TvarA[ncova]=Tvar[k];
                   10148:       TvarAind[ncova]=k;
1.231     brouard  10149:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10150:        Fixed[k]= 2;
                   10151:        Dummy[k]= 2;
                   10152:        modell[k].maintype= ATYPE;
                   10153:        modell[k].subtype= APFD;
                   10154:        /* ncoveff++; */
1.227     brouard  10155:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10156:        Fixed[k]= 2;
                   10157:        Dummy[k]= 3;
                   10158:        modell[k].maintype= ATYPE;
                   10159:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10160:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10161:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10162:        Fixed[k]= 3;
                   10163:        Dummy[k]= 2;
                   10164:        modell[k].maintype= ATYPE;
                   10165:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10166:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10167:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10168:        Fixed[k]= 3;
                   10169:        Dummy[k]= 3;
                   10170:        modell[k].maintype= ATYPE;
                   10171:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10172:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10173:       }
                   10174:     }else if (Typevar[k] == 2) {  /* product without age */
                   10175:       k1=Tposprod[k];
                   10176:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10177:        if(Tvard[k1][2] <=ncovcol){
                   10178:          Fixed[k]= 1;
                   10179:          Dummy[k]= 0;
                   10180:          modell[k].maintype= FTYPE;
                   10181:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10182:          ncovf++; /* Fixed variables without age */
                   10183:          TvarF[ncovf]=Tvar[k];
                   10184:          TvarFind[ncovf]=k;
                   10185:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10186:          Fixed[k]= 0;  /* or 2 ?*/
                   10187:          Dummy[k]= 1;
                   10188:          modell[k].maintype= FTYPE;
                   10189:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10190:          ncovf++; /* Varying variables without age */
                   10191:          TvarF[ncovf]=Tvar[k];
                   10192:          TvarFind[ncovf]=k;
                   10193:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10194:          Fixed[k]= 1;
                   10195:          Dummy[k]= 0;
                   10196:          modell[k].maintype= VTYPE;
                   10197:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10198:          ncovv++; /* Varying variables without age */
                   10199:          TvarV[ncovv]=Tvar[k];
                   10200:          TvarVind[ncovv]=k;
                   10201:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10202:          Fixed[k]= 1;
                   10203:          Dummy[k]= 1;
                   10204:          modell[k].maintype= VTYPE;
                   10205:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10206:          ncovv++; /* Varying variables without age */
                   10207:          TvarV[ncovv]=Tvar[k];
                   10208:          TvarVind[ncovv]=k;
                   10209:        }
1.227     brouard  10210:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10211:        if(Tvard[k1][2] <=ncovcol){
                   10212:          Fixed[k]= 0;  /* or 2 ?*/
                   10213:          Dummy[k]= 1;
                   10214:          modell[k].maintype= FTYPE;
                   10215:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10216:          ncovf++; /* Fixed variables without age */
                   10217:          TvarF[ncovf]=Tvar[k];
                   10218:          TvarFind[ncovf]=k;
                   10219:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10220:          Fixed[k]= 1;
                   10221:          Dummy[k]= 1;
                   10222:          modell[k].maintype= VTYPE;
                   10223:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10224:          ncovv++; /* Varying variables without age */
                   10225:          TvarV[ncovv]=Tvar[k];
                   10226:          TvarVind[ncovv]=k;
                   10227:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10228:          Fixed[k]= 1;
                   10229:          Dummy[k]= 1;
                   10230:          modell[k].maintype= VTYPE;
                   10231:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10232:          ncovv++; /* Varying variables without age */
                   10233:          TvarV[ncovv]=Tvar[k];
                   10234:          TvarVind[ncovv]=k;
                   10235:          ncovv++; /* Varying variables without age */
                   10236:          TvarV[ncovv]=Tvar[k];
                   10237:          TvarVind[ncovv]=k;
                   10238:        }
1.227     brouard  10239:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10240:        if(Tvard[k1][2] <=ncovcol){
                   10241:          Fixed[k]= 1;
                   10242:          Dummy[k]= 1;
                   10243:          modell[k].maintype= VTYPE;
                   10244:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10245:          ncovv++; /* Varying variables without age */
                   10246:          TvarV[ncovv]=Tvar[k];
                   10247:          TvarVind[ncovv]=k;
                   10248:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10249:          Fixed[k]= 1;
                   10250:          Dummy[k]= 1;
                   10251:          modell[k].maintype= VTYPE;
                   10252:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10253:          ncovv++; /* Varying variables without age */
                   10254:          TvarV[ncovv]=Tvar[k];
                   10255:          TvarVind[ncovv]=k;
                   10256:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10257:          Fixed[k]= 1;
                   10258:          Dummy[k]= 0;
                   10259:          modell[k].maintype= VTYPE;
                   10260:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10261:          ncovv++; /* Varying variables without age */
                   10262:          TvarV[ncovv]=Tvar[k];
                   10263:          TvarVind[ncovv]=k;
                   10264:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10265:          Fixed[k]= 1;
                   10266:          Dummy[k]= 1;
                   10267:          modell[k].maintype= VTYPE;
                   10268:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10269:          ncovv++; /* Varying variables without age */
                   10270:          TvarV[ncovv]=Tvar[k];
                   10271:          TvarVind[ncovv]=k;
                   10272:        }
1.227     brouard  10273:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10274:        if(Tvard[k1][2] <=ncovcol){
                   10275:          Fixed[k]= 1;
                   10276:          Dummy[k]= 1;
                   10277:          modell[k].maintype= VTYPE;
                   10278:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10279:          ncovv++; /* Varying variables without age */
                   10280:          TvarV[ncovv]=Tvar[k];
                   10281:          TvarVind[ncovv]=k;
                   10282:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10283:          Fixed[k]= 1;
                   10284:          Dummy[k]= 1;
                   10285:          modell[k].maintype= VTYPE;
                   10286:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10287:          ncovv++; /* Varying variables without age */
                   10288:          TvarV[ncovv]=Tvar[k];
                   10289:          TvarVind[ncovv]=k;
                   10290:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10291:          Fixed[k]= 1;
                   10292:          Dummy[k]= 1;
                   10293:          modell[k].maintype= VTYPE;
                   10294:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10295:          ncovv++; /* Varying variables without age */
                   10296:          TvarV[ncovv]=Tvar[k];
                   10297:          TvarVind[ncovv]=k;
                   10298:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10299:          Fixed[k]= 1;
                   10300:          Dummy[k]= 1;
                   10301:          modell[k].maintype= VTYPE;
                   10302:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10303:          ncovv++; /* Varying variables without age */
                   10304:          TvarV[ncovv]=Tvar[k];
                   10305:          TvarVind[ncovv]=k;
                   10306:        }
1.227     brouard  10307:       }else{
1.240     brouard  10308:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10309:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10310:       } /*end k1*/
1.225     brouard  10311:     }else{
1.226     brouard  10312:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10313:       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  10314:     }
1.227     brouard  10315:     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  10316:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10317:     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]);
                   10318:   }
                   10319:   /* Searching for doublons in the model */
                   10320:   for(k1=1; k1<= cptcovt;k1++){
                   10321:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10322:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10323:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10324:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10325:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10326:            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]);
                   10327:            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  10328:            return(1);
                   10329:          }
                   10330:        }else if (Typevar[k1] ==2){
                   10331:          k3=Tposprod[k1];
                   10332:          k4=Tposprod[k2];
                   10333:          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])) ){
                   10334:            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]]);
                   10335:            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);
                   10336:            return(1);
                   10337:          }
                   10338:        }
1.227     brouard  10339:       }
                   10340:     }
1.225     brouard  10341:   }
                   10342:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10343:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10344:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10345:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10346:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10347:   /*endread:*/
1.225     brouard  10348:   printf("Exiting decodemodel: ");
                   10349:   return (1);
1.136     brouard  10350: }
                   10351: 
1.169     brouard  10352: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10353: {/* Check ages at death */
1.136     brouard  10354:   int i, m;
1.218     brouard  10355:   int firstone=0;
                   10356:   
1.136     brouard  10357:   for (i=1; i<=imx; i++) {
                   10358:     for(m=2; (m<= maxwav); m++) {
                   10359:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10360:        anint[m][i]=9999;
1.216     brouard  10361:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10362:          s[m][i]=-1;
1.136     brouard  10363:       }
                   10364:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10365:        *nberr = *nberr + 1;
1.218     brouard  10366:        if(firstone == 0){
                   10367:          firstone=1;
1.260     brouard  10368:        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  10369:        }
1.262     brouard  10370:        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  10371:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10372:       }
                   10373:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10374:        (*nberr)++;
1.259     brouard  10375:        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  10376:        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  10377:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10378:       }
                   10379:     }
                   10380:   }
                   10381: 
                   10382:   for (i=1; i<=imx; i++)  {
                   10383:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10384:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10385:       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  10386:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10387:          if(agedc[i]>0){
                   10388:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10389:              agev[m][i]=agedc[i];
1.214     brouard  10390:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10391:            }else {
1.136     brouard  10392:              if ((int)andc[i]!=9999){
                   10393:                nbwarn++;
                   10394:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10395:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10396:                agev[m][i]=-1;
                   10397:              }
                   10398:            }
1.169     brouard  10399:          } /* agedc > 0 */
1.214     brouard  10400:        } /* end if */
1.136     brouard  10401:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10402:                                 years but with the precision of a month */
                   10403:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10404:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10405:            agev[m][i]=1;
                   10406:          else if(agev[m][i] < *agemin){ 
                   10407:            *agemin=agev[m][i];
                   10408:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10409:          }
                   10410:          else if(agev[m][i] >*agemax){
                   10411:            *agemax=agev[m][i];
1.156     brouard  10412:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10413:          }
                   10414:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10415:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10416:        } /* en if 9*/
1.136     brouard  10417:        else { /* =9 */
1.214     brouard  10418:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10419:          agev[m][i]=1;
                   10420:          s[m][i]=-1;
                   10421:        }
                   10422:       }
1.214     brouard  10423:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10424:        agev[m][i]=1;
1.214     brouard  10425:       else{
                   10426:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10427:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10428:        agev[m][i]=0;
                   10429:       }
                   10430:     } /* End for lastpass */
                   10431:   }
1.136     brouard  10432:     
                   10433:   for (i=1; i<=imx; i++)  {
                   10434:     for(m=firstpass; (m<=lastpass); m++){
                   10435:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10436:        (*nberr)++;
1.136     brouard  10437:        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);     
                   10438:        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);     
                   10439:        return 1;
                   10440:       }
                   10441:     }
                   10442:   }
                   10443: 
                   10444:   /*for (i=1; i<=imx; i++){
                   10445:   for (m=firstpass; (m<lastpass); m++){
                   10446:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10447: }
                   10448: 
                   10449: }*/
                   10450: 
                   10451: 
1.139     brouard  10452:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10453:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10454: 
                   10455:   return (0);
1.164     brouard  10456:  /* endread:*/
1.136     brouard  10457:     printf("Exiting calandcheckages: ");
                   10458:     return (1);
                   10459: }
                   10460: 
1.172     brouard  10461: #if defined(_MSC_VER)
                   10462: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10463: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10464: //#include "stdafx.h"
                   10465: //#include <stdio.h>
                   10466: //#include <tchar.h>
                   10467: //#include <windows.h>
                   10468: //#include <iostream>
                   10469: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10470: 
                   10471: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10472: 
                   10473: BOOL IsWow64()
                   10474: {
                   10475:        BOOL bIsWow64 = FALSE;
                   10476: 
                   10477:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10478:        //  (HANDLE, PBOOL);
                   10479: 
                   10480:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10481: 
                   10482:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10483:        const char funcName[] = "IsWow64Process";
                   10484:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10485:                GetProcAddress(module, funcName);
                   10486: 
                   10487:        if (NULL != fnIsWow64Process)
                   10488:        {
                   10489:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10490:                        &bIsWow64))
                   10491:                        //throw std::exception("Unknown error");
                   10492:                        printf("Unknown error\n");
                   10493:        }
                   10494:        return bIsWow64 != FALSE;
                   10495: }
                   10496: #endif
1.177     brouard  10497: 
1.191     brouard  10498: void syscompilerinfo(int logged)
1.292     brouard  10499: {
                   10500: #include <stdint.h>
                   10501: 
                   10502:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10503:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10504:    /* /GS /W3 /Gy
                   10505:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10506:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10507:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10508:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10509:    */ 
                   10510:    /* 64 bits */
1.185     brouard  10511:    /*
                   10512:      /GS /W3 /Gy
                   10513:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10514:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10515:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10516:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10517:    /* Optimization are useless and O3 is slower than O2 */
                   10518:    /*
                   10519:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10520:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10521:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10522:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10523:    */
1.186     brouard  10524:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10525:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10526:       /PDB:"visual studio
                   10527:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10528:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10529:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10530:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10531:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10532:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10533:       uiAccess='false'"
                   10534:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10535:       /NOLOGO /TLBID:1
                   10536:    */
1.292     brouard  10537: 
                   10538: 
1.177     brouard  10539: #if defined __INTEL_COMPILER
1.178     brouard  10540: #if defined(__GNUC__)
                   10541:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10542: #endif
1.177     brouard  10543: #elif defined(__GNUC__) 
1.179     brouard  10544: #ifndef  __APPLE__
1.174     brouard  10545: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10546: #endif
1.177     brouard  10547:    struct utsname sysInfo;
1.178     brouard  10548:    int cross = CROSS;
                   10549:    if (cross){
                   10550:           printf("Cross-");
1.191     brouard  10551:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10552:    }
1.174     brouard  10553: #endif
                   10554: 
1.191     brouard  10555:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10556: #if defined(__clang__)
1.191     brouard  10557:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10558: #endif
                   10559: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10560:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10561: #endif
                   10562: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10563:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10564: #endif
                   10565: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10566:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10567: #endif
                   10568: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10569:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10570: #endif
                   10571: #if defined(_MSC_VER)
1.191     brouard  10572:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10573: #endif
                   10574: #if defined(__PGI)
1.191     brouard  10575:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10576: #endif
                   10577: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10578:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10579: #endif
1.191     brouard  10580:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10581:    
1.167     brouard  10582: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10583: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10584:     // Windows (x64 and x86)
1.191     brouard  10585:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10586: #elif __unix__ // all unices, not all compilers
                   10587:     // Unix
1.191     brouard  10588:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10589: #elif __linux__
                   10590:     // linux
1.191     brouard  10591:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10592: #elif __APPLE__
1.174     brouard  10593:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10594:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10595: #endif
                   10596: 
                   10597: /*  __MINGW32__          */
                   10598: /*  __CYGWIN__  */
                   10599: /* __MINGW64__  */
                   10600: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10601: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10602: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10603: /* _WIN64  // Defined for applications for Win64. */
                   10604: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10605: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10606: 
1.167     brouard  10607: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10608:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10609: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10610:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10611: #else
1.191     brouard  10612:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10613: #endif
                   10614: 
1.169     brouard  10615: #if defined(__GNUC__)
                   10616: # if defined(__GNUC_PATCHLEVEL__)
                   10617: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10618:                             + __GNUC_MINOR__ * 100 \
                   10619:                             + __GNUC_PATCHLEVEL__)
                   10620: # else
                   10621: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10622:                             + __GNUC_MINOR__ * 100)
                   10623: # endif
1.174     brouard  10624:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10625:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10626: 
                   10627:    if (uname(&sysInfo) != -1) {
                   10628:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10629:         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  10630:    }
                   10631:    else
                   10632:       perror("uname() error");
1.179     brouard  10633:    //#ifndef __INTEL_COMPILER 
                   10634: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10635:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10636:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10637: #endif
1.169     brouard  10638: #endif
1.172     brouard  10639: 
1.286     brouard  10640:    //   void main ()
1.172     brouard  10641:    //   {
1.169     brouard  10642: #if defined(_MSC_VER)
1.174     brouard  10643:    if (IsWow64()){
1.191     brouard  10644:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10645:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10646:    }
                   10647:    else{
1.191     brouard  10648:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10649:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10650:    }
1.172     brouard  10651:    //     printf("\nPress Enter to continue...");
                   10652:    //     getchar();
                   10653:    //   }
                   10654: 
1.169     brouard  10655: #endif
                   10656:    
1.167     brouard  10657: 
1.219     brouard  10658: }
1.136     brouard  10659: 
1.219     brouard  10660: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10661:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10662:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10663:   /* double ftolpl = 1.e-10; */
1.180     brouard  10664:   double age, agebase, agelim;
1.203     brouard  10665:   double tot;
1.180     brouard  10666: 
1.202     brouard  10667:   strcpy(filerespl,"PL_");
                   10668:   strcat(filerespl,fileresu);
                   10669:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10670:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10671:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10672:   }
1.288     brouard  10673:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10674:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10675:   pstamp(ficrespl);
1.288     brouard  10676:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10677:   fprintf(ficrespl,"#Age ");
                   10678:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10679:   fprintf(ficrespl,"\n");
1.180     brouard  10680:   
1.219     brouard  10681:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10682: 
1.219     brouard  10683:   agebase=ageminpar;
                   10684:   agelim=agemaxpar;
1.180     brouard  10685: 
1.227     brouard  10686:   /* i1=pow(2,ncoveff); */
1.234     brouard  10687:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10688:   if (cptcovn < 1){i1=1;}
1.180     brouard  10689: 
1.238     brouard  10690:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10691:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10692:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10693:        continue;
1.235     brouard  10694: 
1.238     brouard  10695:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10696:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10697:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10698:       /* k=k+1; */
                   10699:       /* to clean */
                   10700:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10701:       fprintf(ficrespl,"#******");
                   10702:       printf("#******");
                   10703:       fprintf(ficlog,"#******");
                   10704:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10705:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10706:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10707:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10708:       }
                   10709:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10710:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10711:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10712:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10713:       }
                   10714:       fprintf(ficrespl,"******\n");
                   10715:       printf("******\n");
                   10716:       fprintf(ficlog,"******\n");
                   10717:       if(invalidvarcomb[k]){
                   10718:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10719:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10720:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10721:        continue;
                   10722:       }
1.219     brouard  10723: 
1.238     brouard  10724:       fprintf(ficrespl,"#Age ");
                   10725:       for(j=1;j<=cptcoveff;j++) {
                   10726:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10727:       }
                   10728:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10729:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10730:     
1.238     brouard  10731:       for (age=agebase; age<=agelim; age++){
                   10732:        /* for (age=agebase; age<=agebase; age++){ */
                   10733:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10734:        fprintf(ficrespl,"%.0f ",age );
                   10735:        for(j=1;j<=cptcoveff;j++)
                   10736:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10737:        tot=0.;
                   10738:        for(i=1; i<=nlstate;i++){
                   10739:          tot +=  prlim[i][i];
                   10740:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10741:        }
                   10742:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10743:       } /* Age */
                   10744:       /* was end of cptcod */
                   10745:     } /* cptcov */
                   10746:   } /* nres */
1.219     brouard  10747:   return 0;
1.180     brouard  10748: }
                   10749: 
1.218     brouard  10750: 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  10751:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10752:        
                   10753:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10754:    * at any age between ageminpar and agemaxpar
                   10755:         */
1.235     brouard  10756:   int i, j, k, i1, nres=0 ;
1.217     brouard  10757:   /* double ftolpl = 1.e-10; */
                   10758:   double age, agebase, agelim;
                   10759:   double tot;
1.218     brouard  10760:   /* double ***mobaverage; */
                   10761:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10762: 
                   10763:   strcpy(fileresplb,"PLB_");
                   10764:   strcat(fileresplb,fileresu);
                   10765:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10766:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10767:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10768:   }
1.288     brouard  10769:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10770:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10771:   pstamp(ficresplb);
1.288     brouard  10772:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10773:   fprintf(ficresplb,"#Age ");
                   10774:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10775:   fprintf(ficresplb,"\n");
                   10776:   
1.218     brouard  10777:   
                   10778:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10779:   
                   10780:   agebase=ageminpar;
                   10781:   agelim=agemaxpar;
                   10782:   
                   10783:   
1.227     brouard  10784:   i1=pow(2,cptcoveff);
1.218     brouard  10785:   if (cptcovn < 1){i1=1;}
1.227     brouard  10786:   
1.238     brouard  10787:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10788:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10789:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10790:        continue;
                   10791:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10792:       fprintf(ficresplb,"#******");
                   10793:       printf("#******");
                   10794:       fprintf(ficlog,"#******");
                   10795:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10796:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10797:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10798:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10799:       }
                   10800:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10801:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10802:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10803:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10804:       }
                   10805:       fprintf(ficresplb,"******\n");
                   10806:       printf("******\n");
                   10807:       fprintf(ficlog,"******\n");
                   10808:       if(invalidvarcomb[k]){
                   10809:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10810:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10811:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10812:        continue;
                   10813:       }
1.218     brouard  10814:     
1.238     brouard  10815:       fprintf(ficresplb,"#Age ");
                   10816:       for(j=1;j<=cptcoveff;j++) {
                   10817:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10818:       }
                   10819:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10820:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10821:     
                   10822:     
1.238     brouard  10823:       for (age=agebase; age<=agelim; age++){
                   10824:        /* for (age=agebase; age<=agebase; age++){ */
                   10825:        if(mobilavproj > 0){
                   10826:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10827:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10828:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10829:        }else if (mobilavproj == 0){
                   10830:          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);
                   10831:          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);
                   10832:          exit(1);
                   10833:        }else{
                   10834:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10835:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10836:          /* printf("TOTOT\n"); */
                   10837:           /* exit(1); */
1.238     brouard  10838:        }
                   10839:        fprintf(ficresplb,"%.0f ",age );
                   10840:        for(j=1;j<=cptcoveff;j++)
                   10841:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10842:        tot=0.;
                   10843:        for(i=1; i<=nlstate;i++){
                   10844:          tot +=  bprlim[i][i];
                   10845:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10846:        }
                   10847:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10848:       } /* Age */
                   10849:       /* was end of cptcod */
1.255     brouard  10850:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10851:     } /* end of any combination */
                   10852:   } /* end of nres */  
1.218     brouard  10853:   /* hBijx(p, bage, fage); */
                   10854:   /* fclose(ficrespijb); */
                   10855:   
                   10856:   return 0;
1.217     brouard  10857: }
1.218     brouard  10858:  
1.180     brouard  10859: int hPijx(double *p, int bage, int fage){
                   10860:     /*------------- h Pij x at various ages ------------*/
                   10861: 
                   10862:   int stepsize;
                   10863:   int agelim;
                   10864:   int hstepm;
                   10865:   int nhstepm;
1.235     brouard  10866:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10867: 
                   10868:   double agedeb;
                   10869:   double ***p3mat;
                   10870: 
1.201     brouard  10871:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10872:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10873:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10874:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10875:     }
                   10876:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10877:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10878:   
                   10879:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10880:     /*if (stepm<=24) stepsize=2;*/
                   10881: 
                   10882:     agelim=AGESUP;
                   10883:     hstepm=stepsize*YEARM; /* Every year of age */
                   10884:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10885:                
1.180     brouard  10886:     /* hstepm=1;   aff par mois*/
                   10887:     pstamp(ficrespij);
                   10888:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10889:     i1= pow(2,cptcoveff);
1.218     brouard  10890:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10891:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10892:                /*      k=k+1;  */
1.235     brouard  10893:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10894:     for(k=1; k<=i1;k++){
1.253     brouard  10895:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10896:        continue;
1.183     brouard  10897:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10898:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10899:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10900:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10901:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10902:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10903:       }
1.183     brouard  10904:       fprintf(ficrespij,"******\n");
                   10905:       
                   10906:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10907:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10908:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10909:        
                   10910:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10911:        
1.183     brouard  10912:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10913:        oldm=oldms;savm=savms;
1.235     brouard  10914:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10915:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10916:        for(i=1; i<=nlstate;i++)
                   10917:          for(j=1; j<=nlstate+ndeath;j++)
                   10918:            fprintf(ficrespij," %1d-%1d",i,j);
                   10919:        fprintf(ficrespij,"\n");
                   10920:        for (h=0; h<=nhstepm; h++){
                   10921:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10922:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10923:          for(i=1; i<=nlstate;i++)
                   10924:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10925:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10926:          fprintf(ficrespij,"\n");
                   10927:        }
1.183     brouard  10928:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10929:        fprintf(ficrespij,"\n");
                   10930:       }
1.180     brouard  10931:       /*}*/
                   10932:     }
1.218     brouard  10933:     return 0;
1.180     brouard  10934: }
1.218     brouard  10935:  
                   10936:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10937:     /*------------- h Bij x at various ages ------------*/
                   10938: 
                   10939:   int stepsize;
1.218     brouard  10940:   /* int agelim; */
                   10941:        int ageminl;
1.217     brouard  10942:   int hstepm;
                   10943:   int nhstepm;
1.238     brouard  10944:   int h, i, i1, j, k, nres;
1.218     brouard  10945:        
1.217     brouard  10946:   double agedeb;
                   10947:   double ***p3mat;
1.218     brouard  10948:        
                   10949:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10950:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10951:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10952:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10953:   }
                   10954:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10955:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10956:   
                   10957:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10958:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10959:   
1.218     brouard  10960:   /* agelim=AGESUP; */
1.289     brouard  10961:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10962:   hstepm=stepsize*YEARM; /* Every year of age */
                   10963:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10964:   
                   10965:   /* hstepm=1;   aff par mois*/
                   10966:   pstamp(ficrespijb);
1.255     brouard  10967:   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  10968:   i1= pow(2,cptcoveff);
1.218     brouard  10969:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10970:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10971:   /*   k=k+1;  */
1.238     brouard  10972:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10973:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10974:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10975:        continue;
                   10976:       fprintf(ficrespijb,"\n#****** ");
                   10977:       for(j=1;j<=cptcoveff;j++)
                   10978:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10979:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10980:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10981:       }
                   10982:       fprintf(ficrespijb,"******\n");
1.264     brouard  10983:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10984:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10985:        continue;
                   10986:       }
                   10987:       
                   10988:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10989:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10990:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  10991:        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 */
                   10992:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  10993:        
                   10994:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10995:        
1.266     brouard  10996:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10997:        /* and memory limitations if stepm is small */
                   10998: 
1.238     brouard  10999:        /* oldm=oldms;savm=savms; */
                   11000:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  11001:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  11002:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11003:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11004:        for(i=1; i<=nlstate;i++)
                   11005:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11006:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11007:        fprintf(ficrespijb,"\n");
1.238     brouard  11008:        for (h=0; h<=nhstepm; h++){
                   11009:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11010:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11011:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11012:          for(i=1; i<=nlstate;i++)
                   11013:            for(j=1; j<=nlstate+ndeath;j++)
                   11014:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   11015:          fprintf(ficrespijb,"\n");
                   11016:        }
                   11017:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11018:        fprintf(ficrespijb,"\n");
                   11019:       } /* end age deb */
                   11020:     } /* end combination */
                   11021:   } /* end nres */
1.218     brouard  11022:   return 0;
                   11023:  } /*  hBijx */
1.217     brouard  11024: 
1.180     brouard  11025: 
1.136     brouard  11026: /***********************************************/
                   11027: /**************** Main Program *****************/
                   11028: /***********************************************/
                   11029: 
                   11030: int main(int argc, char *argv[])
                   11031: {
                   11032: #ifdef GSL
                   11033:   const gsl_multimin_fminimizer_type *T;
                   11034:   size_t iteri = 0, it;
                   11035:   int rval = GSL_CONTINUE;
                   11036:   int status = GSL_SUCCESS;
                   11037:   double ssval;
                   11038: #endif
                   11039:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11040:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11041:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11042:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11043:   int jj, ll, li, lj, lk;
1.136     brouard  11044:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11045:   int num_filled;
1.136     brouard  11046:   int itimes;
                   11047:   int NDIM=2;
                   11048:   int vpopbased=0;
1.235     brouard  11049:   int nres=0;
1.258     brouard  11050:   int endishere=0;
1.277     brouard  11051:   int noffset=0;
1.274     brouard  11052:   int ncurrv=0; /* Temporary variable */
                   11053:   
1.164     brouard  11054:   char ca[32], cb[32];
1.136     brouard  11055:   /*  FILE *fichtm; *//* Html File */
                   11056:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11057:   struct stat info;
1.191     brouard  11058:   double agedeb=0.;
1.194     brouard  11059: 
                   11060:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11061:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11062: 
1.165     brouard  11063:   double fret;
1.191     brouard  11064:   double dum=0.; /* Dummy variable */
1.136     brouard  11065:   double ***p3mat;
1.218     brouard  11066:   /* double ***mobaverage; */
1.164     brouard  11067: 
                   11068:   char line[MAXLINE];
1.197     brouard  11069:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11070: 
1.234     brouard  11071:   char  modeltemp[MAXLINE];
1.230     brouard  11072:   char resultline[MAXLINE];
                   11073:   
1.136     brouard  11074:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11075:   char *tok, *val; /* pathtot */
1.290     brouard  11076:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11077:   int c,  h , cpt, c2;
1.191     brouard  11078:   int jl=0;
                   11079:   int i1, j1, jk, stepsize=0;
1.194     brouard  11080:   int count=0;
                   11081: 
1.164     brouard  11082:   int *tab; 
1.136     brouard  11083:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11084:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11085:   /* double anprojf, mprojf, jprojf; */
                   11086:   /* double jintmean,mintmean,aintmean;   */
                   11087:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11088:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11089:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11090:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11091:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11092:   int mobilav=0,popforecast=0;
1.191     brouard  11093:   int hstepm=0, nhstepm=0;
1.136     brouard  11094:   int agemortsup;
                   11095:   float  sumlpop=0.;
                   11096:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11097:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11098: 
1.191     brouard  11099:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11100:   double ftolpl=FTOL;
                   11101:   double **prlim;
1.217     brouard  11102:   double **bprlim;
1.317   ! brouard  11103:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
        !          11104:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11105:   double ***paramstart; /* Matrix of starting parameter values */
                   11106:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11107:   double **matcov; /* Matrix of covariance */
1.203     brouard  11108:   double **hess; /* Hessian matrix */
1.136     brouard  11109:   double ***delti3; /* Scale */
                   11110:   double *delti; /* Scale */
                   11111:   double ***eij, ***vareij;
                   11112:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11113: 
1.136     brouard  11114:   double *epj, vepp;
1.164     brouard  11115: 
1.273     brouard  11116:   double dateprev1, dateprev2;
1.296     brouard  11117:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11118:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11119: 
1.217     brouard  11120: 
1.136     brouard  11121:   double **ximort;
1.145     brouard  11122:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11123:   int *dcwave;
                   11124: 
1.164     brouard  11125:   char z[1]="c";
1.136     brouard  11126: 
                   11127:   /*char  *strt;*/
                   11128:   char strtend[80];
1.126     brouard  11129: 
1.164     brouard  11130: 
1.126     brouard  11131: /*   setlocale (LC_ALL, ""); */
                   11132: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11133: /*   textdomain (PACKAGE); */
                   11134: /*   setlocale (LC_CTYPE, ""); */
                   11135: /*   setlocale (LC_MESSAGES, ""); */
                   11136: 
                   11137:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11138:   rstart_time = time(NULL);  
                   11139:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11140:   start_time = *localtime(&rstart_time);
1.126     brouard  11141:   curr_time=start_time;
1.157     brouard  11142:   /*tml = *localtime(&start_time.tm_sec);*/
                   11143:   /* strcpy(strstart,asctime(&tml)); */
                   11144:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11145: 
                   11146: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11147: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11148: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11149: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11150: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11151: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11152: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11153: /*   strt=asctime(&tmg); */
                   11154: /*   printf("Time(after) =%s",strstart);  */
                   11155: /*  (void) time (&time_value);
                   11156: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11157: *  tm = *localtime(&time_value);
                   11158: *  strstart=asctime(&tm);
                   11159: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11160: */
                   11161: 
                   11162:   nberr=0; /* Number of errors and warnings */
                   11163:   nbwarn=0;
1.184     brouard  11164: #ifdef WIN32
                   11165:   _getcwd(pathcd, size);
                   11166: #else
1.126     brouard  11167:   getcwd(pathcd, size);
1.184     brouard  11168: #endif
1.191     brouard  11169:   syscompilerinfo(0);
1.196     brouard  11170:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11171:   if(argc <=1){
                   11172:     printf("\nEnter the parameter file name: ");
1.205     brouard  11173:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11174:       printf("ERROR Empty parameter file name\n");
                   11175:       goto end;
                   11176:     }
1.126     brouard  11177:     i=strlen(pathr);
                   11178:     if(pathr[i-1]=='\n')
                   11179:       pathr[i-1]='\0';
1.156     brouard  11180:     i=strlen(pathr);
1.205     brouard  11181:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11182:       pathr[i-1]='\0';
1.205     brouard  11183:     }
                   11184:     i=strlen(pathr);
                   11185:     if( i==0 ){
                   11186:       printf("ERROR Empty parameter file name\n");
                   11187:       goto end;
                   11188:     }
                   11189:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11190:       printf("Pathr |%s|\n",pathr);
                   11191:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11192:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11193:       strcpy (pathtot, val);
                   11194:       if(pathr[0] == '\0') break; /* Dirty */
                   11195:     }
                   11196:   }
1.281     brouard  11197:   else if (argc<=2){
                   11198:     strcpy(pathtot,argv[1]);
                   11199:   }
1.126     brouard  11200:   else{
                   11201:     strcpy(pathtot,argv[1]);
1.281     brouard  11202:     strcpy(z,argv[2]);
                   11203:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11204:   }
                   11205:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11206:   /*cygwin_split_path(pathtot,path,optionfile);
                   11207:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11208:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11209: 
                   11210:   /* Split argv[0], imach program to get pathimach */
                   11211:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11212:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11213:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11214:  /*   strcpy(pathimach,argv[0]); */
                   11215:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11216:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11217:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11218: #ifdef WIN32
                   11219:   _chdir(path); /* Can be a relative path */
                   11220:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11221: #else
1.126     brouard  11222:   chdir(path); /* Can be a relative path */
1.184     brouard  11223:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11224: #endif
                   11225:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11226:   strcpy(command,"mkdir ");
                   11227:   strcat(command,optionfilefiname);
                   11228:   if((outcmd=system(command)) != 0){
1.169     brouard  11229:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11230:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11231:     /* fclose(ficlog); */
                   11232: /*     exit(1); */
                   11233:   }
                   11234: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11235: /*     perror("mkdir"); */
                   11236: /*   } */
                   11237: 
                   11238:   /*-------- arguments in the command line --------*/
                   11239: 
1.186     brouard  11240:   /* Main Log file */
1.126     brouard  11241:   strcat(filelog, optionfilefiname);
                   11242:   strcat(filelog,".log");    /* */
                   11243:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11244:     printf("Problem with logfile %s\n",filelog);
                   11245:     goto end;
                   11246:   }
                   11247:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11248:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11249:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11250:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11251:  path=%s \n\
                   11252:  optionfile=%s\n\
                   11253:  optionfilext=%s\n\
1.156     brouard  11254:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11255: 
1.197     brouard  11256:   syscompilerinfo(1);
1.167     brouard  11257: 
1.126     brouard  11258:   printf("Local time (at start):%s",strstart);
                   11259:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11260:   fflush(ficlog);
                   11261: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11262: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11263: 
                   11264:   /* */
                   11265:   strcpy(fileres,"r");
                   11266:   strcat(fileres, optionfilefiname);
1.201     brouard  11267:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11268:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11269:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11270: 
1.186     brouard  11271:   /* Main ---------arguments file --------*/
1.126     brouard  11272: 
                   11273:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11274:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11275:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11276:     fflush(ficlog);
1.149     brouard  11277:     /* goto end; */
                   11278:     exit(70); 
1.126     brouard  11279:   }
                   11280: 
                   11281:   strcpy(filereso,"o");
1.201     brouard  11282:   strcat(filereso,fileresu);
1.126     brouard  11283:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11284:     printf("Problem with Output resultfile: %s\n", filereso);
                   11285:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11286:     fflush(ficlog);
                   11287:     goto end;
                   11288:   }
1.278     brouard  11289:       /*-------- Rewriting parameter file ----------*/
                   11290:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11291:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11292:   strcat(rfileres,".");    /* */
                   11293:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11294:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11295:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11296:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11297:     fflush(ficlog);
                   11298:     goto end;
                   11299:   }
                   11300:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11301: 
1.278     brouard  11302:                                      
1.126     brouard  11303:   /* Reads comments: lines beginning with '#' */
                   11304:   numlinepar=0;
1.277     brouard  11305:   /* Is it a BOM UTF-8 Windows file? */
                   11306:   /* First parameter line */
1.197     brouard  11307:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11308:     noffset=0;
                   11309:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11310:     {
                   11311:       noffset=noffset+3;
                   11312:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11313:     }
1.302     brouard  11314: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11315:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11316:     {
                   11317:       noffset=noffset+2;
                   11318:       printf("# File is an UTF16BE BOM file\n");
                   11319:     }
                   11320:     else if( line[0] == 0 && line[1] == 0)
                   11321:     {
                   11322:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11323:        noffset=noffset+4;
                   11324:        printf("# File is an UTF16BE BOM file\n");
                   11325:       }
                   11326:     } else{
                   11327:       ;/*printf(" Not a BOM file\n");*/
                   11328:     }
                   11329:   
1.197     brouard  11330:     /* If line starts with a # it is a comment */
1.277     brouard  11331:     if (line[noffset] == '#') {
1.197     brouard  11332:       numlinepar++;
                   11333:       fputs(line,stdout);
                   11334:       fputs(line,ficparo);
1.278     brouard  11335:       fputs(line,ficres);
1.197     brouard  11336:       fputs(line,ficlog);
                   11337:       continue;
                   11338:     }else
                   11339:       break;
                   11340:   }
                   11341:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11342:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11343:     if (num_filled != 5) {
                   11344:       printf("Should be 5 parameters\n");
1.283     brouard  11345:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11346:     }
1.126     brouard  11347:     numlinepar++;
1.197     brouard  11348:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11349:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11350:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11351:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11352:   }
                   11353:   /* Second parameter line */
                   11354:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11355:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11356:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11357:     if (line[0] == '#') {
                   11358:       numlinepar++;
1.283     brouard  11359:       printf("%s",line);
                   11360:       fprintf(ficres,"%s",line);
                   11361:       fprintf(ficparo,"%s",line);
                   11362:       fprintf(ficlog,"%s",line);
1.197     brouard  11363:       continue;
                   11364:     }else
                   11365:       break;
                   11366:   }
1.223     brouard  11367:   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", \
                   11368:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11369:     if (num_filled != 11) {
                   11370:       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  11371:       printf("but line=%s\n",line);
1.283     brouard  11372:       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");
                   11373:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11374:     }
1.286     brouard  11375:     if( lastpass > maxwav){
                   11376:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11377:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11378:       fflush(ficlog);
                   11379:       goto end;
                   11380:     }
                   11381:       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  11382:     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  11383:     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  11384:     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  11385:   }
1.203     brouard  11386:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11387:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11388:   /* Third parameter line */
                   11389:   while(fgets(line, MAXLINE, ficpar)) {
                   11390:     /* If line starts with a # it is a comment */
                   11391:     if (line[0] == '#') {
                   11392:       numlinepar++;
1.283     brouard  11393:       printf("%s",line);
                   11394:       fprintf(ficres,"%s",line);
                   11395:       fprintf(ficparo,"%s",line);
                   11396:       fprintf(ficlog,"%s",line);
1.197     brouard  11397:       continue;
                   11398:     }else
                   11399:       break;
                   11400:   }
1.201     brouard  11401:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11402:     if (num_filled != 1){
1.302     brouard  11403:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11404:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11405:       model[0]='\0';
                   11406:       goto end;
                   11407:     }
                   11408:     else{
                   11409:       if (model[0]=='+'){
                   11410:        for(i=1; i<=strlen(model);i++)
                   11411:          modeltemp[i-1]=model[i];
1.201     brouard  11412:        strcpy(model,modeltemp); 
1.197     brouard  11413:       }
                   11414:     }
1.199     brouard  11415:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11416:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11417:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11418:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11419:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11420:   }
                   11421:   /* 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); */
                   11422:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11423:   /* 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  11424:   /* 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); */
                   11425:   /* 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  11426:   fflush(ficlog);
1.190     brouard  11427:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11428:   if(model[0]=='#'){
1.279     brouard  11429:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11430:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11431:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11432:     if(mle != -1){
1.279     brouard  11433:       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  11434:       exit(1);
                   11435:     }
                   11436:   }
1.126     brouard  11437:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11438:     ungetc(c,ficpar);
                   11439:     fgets(line, MAXLINE, ficpar);
                   11440:     numlinepar++;
1.195     brouard  11441:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11442:       z[0]=line[1];
                   11443:     }
                   11444:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11445:     fputs(line, stdout);
                   11446:     //puts(line);
1.126     brouard  11447:     fputs(line,ficparo);
                   11448:     fputs(line,ficlog);
                   11449:   }
                   11450:   ungetc(c,ficpar);
                   11451: 
                   11452:    
1.290     brouard  11453:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11454:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11455:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11456:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11457:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11458:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11459:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11460:   */
                   11461:   if (strlen(model)>1) 
1.187     brouard  11462:     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  11463:   else
1.187     brouard  11464:     ncovmodel=2; /* Constant and age */
1.133     brouard  11465:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11466:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11467:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11468:     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);
                   11469:     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);
                   11470:     fflush(stdout);
                   11471:     fclose (ficlog);
                   11472:     goto end;
                   11473:   }
1.126     brouard  11474:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11475:   delti=delti3[1][1];
                   11476:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11477:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11478: /* We could also provide initial parameters values giving by simple logistic regression 
                   11479:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11480:       /* for(i=1;i<nlstate;i++){ */
                   11481:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11482:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11483:       /* } */
1.126     brouard  11484:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11485:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11486:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11487:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11488:     fclose (ficparo);
                   11489:     fclose (ficlog);
                   11490:     goto end;
                   11491:     exit(0);
1.220     brouard  11492:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11493:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11494:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11495:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11496:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11497:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11498:     hess=matrix(1,npar,1,npar);
1.220     brouard  11499:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11500:     /* Read guessed parameters */
1.126     brouard  11501:     /* Reads comments: lines beginning with '#' */
                   11502:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11503:       ungetc(c,ficpar);
                   11504:       fgets(line, MAXLINE, ficpar);
                   11505:       numlinepar++;
1.141     brouard  11506:       fputs(line,stdout);
1.126     brouard  11507:       fputs(line,ficparo);
                   11508:       fputs(line,ficlog);
                   11509:     }
                   11510:     ungetc(c,ficpar);
                   11511:     
                   11512:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11513:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11514:     for(i=1; i <=nlstate; i++){
1.234     brouard  11515:       j=0;
1.126     brouard  11516:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11517:        if(jj==i) continue;
                   11518:        j++;
1.292     brouard  11519:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11520:          ungetc(c,ficpar);
                   11521:          fgets(line, MAXLINE, ficpar);
                   11522:          numlinepar++;
                   11523:          fputs(line,stdout);
                   11524:          fputs(line,ficparo);
                   11525:          fputs(line,ficlog);
                   11526:        }
                   11527:        ungetc(c,ficpar);
1.234     brouard  11528:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11529:        if ((i1 != i) || (j1 != jj)){
                   11530:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11531: It might be a problem of design; if ncovcol and the model are correct\n \
                   11532: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11533:          exit(1);
                   11534:        }
                   11535:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11536:        if(mle==1)
                   11537:          printf("%1d%1d",i,jj);
                   11538:        fprintf(ficlog,"%1d%1d",i,jj);
                   11539:        for(k=1; k<=ncovmodel;k++){
                   11540:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11541:          if(mle==1){
                   11542:            printf(" %lf",param[i][j][k]);
                   11543:            fprintf(ficlog," %lf",param[i][j][k]);
                   11544:          }
                   11545:          else
                   11546:            fprintf(ficlog," %lf",param[i][j][k]);
                   11547:          fprintf(ficparo," %lf",param[i][j][k]);
                   11548:        }
                   11549:        fscanf(ficpar,"\n");
                   11550:        numlinepar++;
                   11551:        if(mle==1)
                   11552:          printf("\n");
                   11553:        fprintf(ficlog,"\n");
                   11554:        fprintf(ficparo,"\n");
1.126     brouard  11555:       }
                   11556:     }  
                   11557:     fflush(ficlog);
1.234     brouard  11558:     
1.251     brouard  11559:     /* Reads parameters values */
1.126     brouard  11560:     p=param[1][1];
1.251     brouard  11561:     pstart=paramstart[1][1];
1.126     brouard  11562:     
                   11563:     /* Reads comments: lines beginning with '#' */
                   11564:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11565:       ungetc(c,ficpar);
                   11566:       fgets(line, MAXLINE, ficpar);
                   11567:       numlinepar++;
1.141     brouard  11568:       fputs(line,stdout);
1.126     brouard  11569:       fputs(line,ficparo);
                   11570:       fputs(line,ficlog);
                   11571:     }
                   11572:     ungetc(c,ficpar);
                   11573: 
                   11574:     for(i=1; i <=nlstate; i++){
                   11575:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11576:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11577:        if ( (i1-i) * (j1-j) != 0){
                   11578:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11579:          exit(1);
                   11580:        }
                   11581:        printf("%1d%1d",i,j);
                   11582:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11583:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11584:        for(k=1; k<=ncovmodel;k++){
                   11585:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11586:          printf(" %le",delti3[i][j][k]);
                   11587:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11588:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11589:        }
                   11590:        fscanf(ficpar,"\n");
                   11591:        numlinepar++;
                   11592:        printf("\n");
                   11593:        fprintf(ficparo,"\n");
                   11594:        fprintf(ficlog,"\n");
1.126     brouard  11595:       }
                   11596:     }
                   11597:     fflush(ficlog);
1.234     brouard  11598:     
1.145     brouard  11599:     /* Reads covariance matrix */
1.126     brouard  11600:     delti=delti3[1][1];
1.220     brouard  11601:                
                   11602:                
1.126     brouard  11603:     /* 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  11604:                
1.126     brouard  11605:     /* Reads comments: lines beginning with '#' */
                   11606:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11607:       ungetc(c,ficpar);
                   11608:       fgets(line, MAXLINE, ficpar);
                   11609:       numlinepar++;
1.141     brouard  11610:       fputs(line,stdout);
1.126     brouard  11611:       fputs(line,ficparo);
                   11612:       fputs(line,ficlog);
                   11613:     }
                   11614:     ungetc(c,ficpar);
1.220     brouard  11615:                
1.126     brouard  11616:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11617:     hess=matrix(1,npar,1,npar);
1.131     brouard  11618:     for(i=1; i <=npar; i++)
                   11619:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11620:                
1.194     brouard  11621:     /* Scans npar lines */
1.126     brouard  11622:     for(i=1; i <=npar; i++){
1.226     brouard  11623:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11624:       if(count != 3){
1.226     brouard  11625:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11626: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11627: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11628:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11629: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11630: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11631:        exit(1);
1.220     brouard  11632:       }else{
1.226     brouard  11633:        if(mle==1)
                   11634:          printf("%1d%1d%d",i1,j1,jk);
                   11635:       }
                   11636:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11637:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11638:       for(j=1; j <=i; j++){
1.226     brouard  11639:        fscanf(ficpar," %le",&matcov[i][j]);
                   11640:        if(mle==1){
                   11641:          printf(" %.5le",matcov[i][j]);
                   11642:        }
                   11643:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11644:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11645:       }
                   11646:       fscanf(ficpar,"\n");
                   11647:       numlinepar++;
                   11648:       if(mle==1)
1.220     brouard  11649:                                printf("\n");
1.126     brouard  11650:       fprintf(ficlog,"\n");
                   11651:       fprintf(ficparo,"\n");
                   11652:     }
1.194     brouard  11653:     /* End of read covariance matrix npar lines */
1.126     brouard  11654:     for(i=1; i <=npar; i++)
                   11655:       for(j=i+1;j<=npar;j++)
1.226     brouard  11656:        matcov[i][j]=matcov[j][i];
1.126     brouard  11657:     
                   11658:     if(mle==1)
                   11659:       printf("\n");
                   11660:     fprintf(ficlog,"\n");
                   11661:     
                   11662:     fflush(ficlog);
                   11663:     
                   11664:   }    /* End of mle != -3 */
1.218     brouard  11665:   
1.186     brouard  11666:   /*  Main data
                   11667:    */
1.290     brouard  11668:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11669:   /* num=lvector(1,n); */
                   11670:   /* moisnais=vector(1,n); */
                   11671:   /* annais=vector(1,n); */
                   11672:   /* moisdc=vector(1,n); */
                   11673:   /* andc=vector(1,n); */
                   11674:   /* weight=vector(1,n); */
                   11675:   /* agedc=vector(1,n); */
                   11676:   /* cod=ivector(1,n); */
                   11677:   /* for(i=1;i<=n;i++){ */
                   11678:   num=lvector(firstobs,lastobs);
                   11679:   moisnais=vector(firstobs,lastobs);
                   11680:   annais=vector(firstobs,lastobs);
                   11681:   moisdc=vector(firstobs,lastobs);
                   11682:   andc=vector(firstobs,lastobs);
                   11683:   weight=vector(firstobs,lastobs);
                   11684:   agedc=vector(firstobs,lastobs);
                   11685:   cod=ivector(firstobs,lastobs);
                   11686:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11687:     num[i]=0;
                   11688:     moisnais[i]=0;
                   11689:     annais[i]=0;
                   11690:     moisdc[i]=0;
                   11691:     andc[i]=0;
                   11692:     agedc[i]=0;
                   11693:     cod[i]=0;
                   11694:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11695:   }
1.290     brouard  11696:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11697:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11698:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11699:   tab=ivector(1,NCOVMAX);
1.144     brouard  11700:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11701:   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  11702: 
1.136     brouard  11703:   /* Reads data from file datafile */
                   11704:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11705:     goto end;
                   11706: 
                   11707:   /* Calculation of the number of parameters from char model */
1.234     brouard  11708:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11709:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11710:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11711:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11712:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11713:   */
                   11714:   
                   11715:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11716:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11717:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11718:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11719:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11720:   TvarF=ivector(1,NCOVMAX); /*  */
                   11721:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11722:   TvarV=ivector(1,NCOVMAX); /*  */
                   11723:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11724:   TvarA=ivector(1,NCOVMAX); /*  */
                   11725:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11726:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11727:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11728:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11729:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11730:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11731:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11732:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11733:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11734: 
1.230     brouard  11735:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11736:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11737:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11738:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11739:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11740:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11741:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11742:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11743:   */
                   11744:   /* For model-covariate k tells which data-covariate to use but
                   11745:     because this model-covariate is a construction we invent a new column
                   11746:     ncovcol + k1
                   11747:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11748:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11749:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11750:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11751:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11752:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11753:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11754:   */
1.145     brouard  11755:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11756:   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  11757:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11758:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11759:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11760:                         4 covariates (3 plus signs)
                   11761:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11762:                      */  
1.230     brouard  11763:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11764:                                * individual dummy, fixed or varying:
                   11765:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11766:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11767:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11768:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11769:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11770:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11771:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11772:                                * individual quantitative, fixed or varying:
                   11773:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11774:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11775:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11776: /* Main decodemodel */
                   11777: 
1.187     brouard  11778: 
1.223     brouard  11779:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11780:     goto end;
                   11781: 
1.137     brouard  11782:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11783:     nbwarn++;
                   11784:     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); 
                   11785:     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); 
                   11786:   }
1.136     brouard  11787:     /*  if(mle==1){*/
1.137     brouard  11788:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11789:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11790:   }
                   11791: 
                   11792:     /*-calculation of age at interview from date of interview and age at death -*/
                   11793:   agev=matrix(1,maxwav,1,imx);
                   11794: 
                   11795:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11796:     goto end;
                   11797: 
1.126     brouard  11798: 
1.136     brouard  11799:   agegomp=(int)agemin;
1.290     brouard  11800:   free_vector(moisnais,firstobs,lastobs);
                   11801:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11802:   /* free_matrix(mint,1,maxwav,1,n);
                   11803:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11804:   /* free_vector(moisdc,1,n); */
                   11805:   /* free_vector(andc,1,n); */
1.145     brouard  11806:   /* */
                   11807:   
1.126     brouard  11808:   wav=ivector(1,imx);
1.214     brouard  11809:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11810:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11811:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11812:   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.*/
                   11813:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11814:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11815:    
                   11816:   /* Concatenates waves */
1.214     brouard  11817:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11818:      Death is a valid wave (if date is known).
                   11819:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11820:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11821:      and mw[mi+1][i]. dh depends on stepm.
                   11822:   */
                   11823: 
1.126     brouard  11824:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11825:   /* Concatenates waves */
1.145     brouard  11826:  
1.290     brouard  11827:   free_vector(moisdc,firstobs,lastobs);
                   11828:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11829: 
1.126     brouard  11830:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11831:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11832:   ncodemax[1]=1;
1.145     brouard  11833:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11834:   cptcoveff=0;
1.220     brouard  11835:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11836:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11837:   }
                   11838:   
                   11839:   ncovcombmax=pow(2,cptcoveff);
                   11840:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11841:   for(i=1;i<ncovcombmax;i++)
                   11842:     invalidvarcomb[i]=0;
                   11843:   
1.211     brouard  11844:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11845:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11846:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11847:   
1.200     brouard  11848:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11849:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11850:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11851:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11852:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11853:    * (currently 0 or 1) in the data.
                   11854:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11855:    * corresponding modality (h,j).
                   11856:    */
                   11857: 
1.145     brouard  11858:   h=0;
                   11859:   /*if (cptcovn > 0) */
1.126     brouard  11860:   m=pow(2,cptcoveff);
                   11861:  
1.144     brouard  11862:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11863:           * For k=4 covariates, h goes from 1 to m=2**k
                   11864:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11865:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11866:           *     h\k   1     2     3     4
1.143     brouard  11867:           *______________________________  
                   11868:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11869:           *     2     2     1     1     1
                   11870:           *     3 i=2 1     2     1     1
                   11871:           *     4     2     2     1     1
                   11872:           *     5 i=3 1 i=2 1     2     1
                   11873:           *     6     2     1     2     1
                   11874:           *     7 i=4 1     2     2     1
                   11875:           *     8     2     2     2     1
1.197     brouard  11876:           *     9 i=5 1 i=3 1 i=2 1     2
                   11877:           *    10     2     1     1     2
                   11878:           *    11 i=6 1     2     1     2
                   11879:           *    12     2     2     1     2
                   11880:           *    13 i=7 1 i=4 1     2     2    
                   11881:           *    14     2     1     2     2
                   11882:           *    15 i=8 1     2     2     2
                   11883:           *    16     2     2     2     2
1.143     brouard  11884:           */
1.212     brouard  11885:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11886:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11887:      * and the value of each covariate?
                   11888:      * V1=1, V2=1, V3=2, V4=1 ?
                   11889:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11890:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11891:      * In order to get the real value in the data, we use nbcode
                   11892:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11893:      * We are keeping this crazy system in order to be able (in the future?) 
                   11894:      * to have more than 2 values (0 or 1) for a covariate.
                   11895:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11896:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11897:      *              bbbbbbbb
                   11898:      *              76543210     
                   11899:      *   h-1        00000101 (6-1=5)
1.219     brouard  11900:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11901:      *           &
                   11902:      *     1        00000001 (1)
1.219     brouard  11903:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11904:      *          +1= 00000001 =1 
1.211     brouard  11905:      *
                   11906:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11907:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11908:      *    >>k'            11
                   11909:      *          &   00000001
                   11910:      *            = 00000001
                   11911:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11912:      * Reverse h=6 and m=16?
                   11913:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11914:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11915:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11916:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11917:      * V3=decodtabm(14,3,2**4)=2
                   11918:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11919:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11920:      *          &1 000000001
                   11921:      *           = 000000001
                   11922:      *         +1= 000000010 =2
                   11923:      *                  2211
                   11924:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11925:      *                  V3=2
1.220     brouard  11926:                 * codtabm and decodtabm are identical
1.211     brouard  11927:      */
                   11928: 
1.145     brouard  11929: 
                   11930:  free_ivector(Ndum,-1,NCOVMAX);
                   11931: 
                   11932: 
1.126     brouard  11933:     
1.186     brouard  11934:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11935:   strcpy(optionfilegnuplot,optionfilefiname);
                   11936:   if(mle==-3)
1.201     brouard  11937:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11938:   strcat(optionfilegnuplot,".gp");
                   11939: 
                   11940:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11941:     printf("Problem with file %s",optionfilegnuplot);
                   11942:   }
                   11943:   else{
1.204     brouard  11944:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11945:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11946:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11947:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11948:   }
                   11949:   /*  fclose(ficgp);*/
1.186     brouard  11950: 
                   11951: 
                   11952:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11953: 
                   11954:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11955:   if(mle==-3)
1.201     brouard  11956:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11957:   strcat(optionfilehtm,".htm");
                   11958:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11959:     printf("Problem with %s \n",optionfilehtm);
                   11960:     exit(0);
1.126     brouard  11961:   }
                   11962: 
                   11963:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11964:   strcat(optionfilehtmcov,"-cov.htm");
                   11965:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11966:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11967:   }
                   11968:   else{
                   11969:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11970: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11971: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11972:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11973:   }
                   11974: 
1.213     brouard  11975:   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  11976: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11977: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11978: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11979: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11980: \n\
                   11981: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11982:  <ul><li><h4>Parameter files</h4>\n\
                   11983:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11984:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11985:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11986:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11987:  - Date and time at start: %s</ul>\n",\
                   11988:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11989:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11990:          fileres,fileres,\
                   11991:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11992:   fflush(fichtm);
                   11993: 
                   11994:   strcpy(pathr,path);
                   11995:   strcat(pathr,optionfilefiname);
1.184     brouard  11996: #ifdef WIN32
                   11997:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11998: #else
1.126     brouard  11999:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12000: #endif
                   12001:          
1.126     brouard  12002:   
1.220     brouard  12003:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12004:                 and for any valid combination of covariates
1.126     brouard  12005:      and prints on file fileres'p'. */
1.251     brouard  12006:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12007:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12008: 
                   12009:   fprintf(fichtm,"\n");
1.286     brouard  12010:   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  12011:          ftol, stepm);
                   12012:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12013:   ncurrv=1;
                   12014:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12015:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12016:   ncurrv=i;
                   12017:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12018:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12019:   ncurrv=i;
                   12020:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12021:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12022:   ncurrv=i;
                   12023:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12024:   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", \
                   12025:           nlstate, ndeath, maxwav, mle, weightopt);
                   12026: 
                   12027:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12028: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12029: 
                   12030:   
1.317   ! brouard  12031:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12032: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12033: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12034:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12035:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12036:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12037:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12038:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12039:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12040: 
1.126     brouard  12041:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12042:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12043:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12044: 
                   12045:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12046:   /* For mortality only */
1.126     brouard  12047:   if (mle==-3){
1.136     brouard  12048:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12049:     for(i=1;i<=NDIM;i++)
                   12050:       for(j=1;j<=NDIM;j++)
                   12051:        ximort[i][j]=0.;
1.186     brouard  12052:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12053:     cens=ivector(firstobs,lastobs);
                   12054:     ageexmed=vector(firstobs,lastobs);
                   12055:     agecens=vector(firstobs,lastobs);
                   12056:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12057:                
1.126     brouard  12058:     for (i=1; i<=imx; i++){
                   12059:       dcwave[i]=-1;
                   12060:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12061:        if (s[m][i]>nlstate) {
                   12062:          dcwave[i]=m;
                   12063:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12064:          break;
                   12065:        }
1.126     brouard  12066:     }
1.226     brouard  12067:     
1.126     brouard  12068:     for (i=1; i<=imx; i++) {
                   12069:       if (wav[i]>0){
1.226     brouard  12070:        ageexmed[i]=agev[mw[1][i]][i];
                   12071:        j=wav[i];
                   12072:        agecens[i]=1.; 
                   12073:        
                   12074:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12075:          agecens[i]=agev[mw[j][i]][i];
                   12076:          cens[i]= 1;
                   12077:        }else if (ageexmed[i]< 1) 
                   12078:          cens[i]= -1;
                   12079:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12080:          cens[i]=0 ;
1.126     brouard  12081:       }
                   12082:       else cens[i]=-1;
                   12083:     }
                   12084:     
                   12085:     for (i=1;i<=NDIM;i++) {
                   12086:       for (j=1;j<=NDIM;j++)
1.226     brouard  12087:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12088:     }
                   12089:     
1.302     brouard  12090:     p[1]=0.0268; p[NDIM]=0.083;
                   12091:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12092:     
                   12093:     
1.136     brouard  12094: #ifdef GSL
                   12095:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12096: #else
1.126     brouard  12097:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12098: #endif
1.201     brouard  12099:     strcpy(filerespow,"POW-MORT_"); 
                   12100:     strcat(filerespow,fileresu);
1.126     brouard  12101:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12102:       printf("Problem with resultfile: %s\n", filerespow);
                   12103:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12104:     }
1.136     brouard  12105: #ifdef GSL
                   12106:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12107: #else
1.126     brouard  12108:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12109: #endif
1.126     brouard  12110:     /*  for (i=1;i<=nlstate;i++)
                   12111:        for(j=1;j<=nlstate+ndeath;j++)
                   12112:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12113:     */
                   12114:     fprintf(ficrespow,"\n");
1.136     brouard  12115: #ifdef GSL
                   12116:     /* gsl starts here */ 
                   12117:     T = gsl_multimin_fminimizer_nmsimplex;
                   12118:     gsl_multimin_fminimizer *sfm = NULL;
                   12119:     gsl_vector *ss, *x;
                   12120:     gsl_multimin_function minex_func;
                   12121: 
                   12122:     /* Initial vertex size vector */
                   12123:     ss = gsl_vector_alloc (NDIM);
                   12124:     
                   12125:     if (ss == NULL){
                   12126:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12127:     }
                   12128:     /* Set all step sizes to 1 */
                   12129:     gsl_vector_set_all (ss, 0.001);
                   12130: 
                   12131:     /* Starting point */
1.126     brouard  12132:     
1.136     brouard  12133:     x = gsl_vector_alloc (NDIM);
                   12134:     
                   12135:     if (x == NULL){
                   12136:       gsl_vector_free(ss);
                   12137:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12138:     }
                   12139:   
                   12140:     /* Initialize method and iterate */
                   12141:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12142:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12143:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12144:     gsl_vector_set(x, 0, p[1]);
                   12145:     gsl_vector_set(x, 1, p[2]);
                   12146: 
                   12147:     minex_func.f = &gompertz_f;
                   12148:     minex_func.n = NDIM;
                   12149:     minex_func.params = (void *)&p; /* ??? */
                   12150:     
                   12151:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12152:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12153:     
                   12154:     printf("Iterations beginning .....\n\n");
                   12155:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12156: 
                   12157:     iteri=0;
                   12158:     while (rval == GSL_CONTINUE){
                   12159:       iteri++;
                   12160:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12161:       
                   12162:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12163:       fflush(0);
                   12164:       
                   12165:       if (status) 
                   12166:         break;
                   12167:       
                   12168:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12169:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12170:       
                   12171:       if (rval == GSL_SUCCESS)
                   12172:         printf ("converged to a local maximum at\n");
                   12173:       
                   12174:       printf("%5d ", iteri);
                   12175:       for (it = 0; it < NDIM; it++){
                   12176:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12177:       }
                   12178:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12179:     }
                   12180:     
                   12181:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12182:     
                   12183:     gsl_vector_free(x); /* initial values */
                   12184:     gsl_vector_free(ss); /* inital step size */
                   12185:     for (it=0; it<NDIM; it++){
                   12186:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12187:       fprintf(ficrespow," %.12lf", p[it]);
                   12188:     }
                   12189:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12190: #endif
                   12191: #ifdef POWELL
                   12192:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12193: #endif  
1.126     brouard  12194:     fclose(ficrespow);
                   12195:     
1.203     brouard  12196:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12197: 
                   12198:     for(i=1; i <=NDIM; i++)
                   12199:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12200:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12201:     
                   12202:     printf("\nCovariance matrix\n ");
1.203     brouard  12203:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12204:     for(i=1; i <=NDIM; i++) {
                   12205:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12206:                                printf("%f ",matcov[i][j]);
                   12207:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12208:       }
1.203     brouard  12209:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12210:     }
                   12211:     
                   12212:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12213:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12214:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12215:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12216:     }
1.302     brouard  12217:     lsurv=vector(agegomp,AGESUP);
                   12218:     lpop=vector(agegomp,AGESUP);
                   12219:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12220:     lsurv[agegomp]=100000;
                   12221:     
                   12222:     for (k=agegomp;k<=AGESUP;k++) {
                   12223:       agemortsup=k;
                   12224:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12225:     }
                   12226:     
                   12227:     for (k=agegomp;k<agemortsup;k++)
                   12228:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12229:     
                   12230:     for (k=agegomp;k<agemortsup;k++){
                   12231:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12232:       sumlpop=sumlpop+lpop[k];
                   12233:     }
                   12234:     
                   12235:     tpop[agegomp]=sumlpop;
                   12236:     for (k=agegomp;k<(agemortsup-3);k++){
                   12237:       /*  tpop[k+1]=2;*/
                   12238:       tpop[k+1]=tpop[k]-lpop[k];
                   12239:     }
                   12240:     
                   12241:     
                   12242:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12243:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12244:       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]);
                   12245:     
                   12246:     
                   12247:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12248:                ageminpar=50;
                   12249:                agemaxpar=100;
1.194     brouard  12250:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12251:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12252: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12253: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12254:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12255: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12256: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12257:     }else{
                   12258:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12259:                        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  12260:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12261:                }
1.201     brouard  12262:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12263:                     stepm, weightopt,\
                   12264:                     model,imx,p,matcov,agemortsup);
                   12265:     
1.302     brouard  12266:     free_vector(lsurv,agegomp,AGESUP);
                   12267:     free_vector(lpop,agegomp,AGESUP);
                   12268:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12269:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12270:     free_ivector(dcwave,firstobs,lastobs);
                   12271:     free_vector(agecens,firstobs,lastobs);
                   12272:     free_vector(ageexmed,firstobs,lastobs);
                   12273:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12274: #ifdef GSL
1.136     brouard  12275: #endif
1.186     brouard  12276:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12277:   /* Standard  */
                   12278:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12279:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12280:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12281:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12282:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12283:     for (k=1; k<=npar;k++)
                   12284:       printf(" %d %8.5f",k,p[k]);
                   12285:     printf("\n");
1.205     brouard  12286:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12287:       /* mlikeli uses func not funcone */
1.247     brouard  12288:       /* for(i=1;i<nlstate;i++){ */
                   12289:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12290:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12291:       /* } */
1.205     brouard  12292:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12293:     }
                   12294:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12295:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12296:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12297:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12298:     }
                   12299:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12300:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12301:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12302:     for (k=1; k<=npar;k++)
                   12303:       printf(" %d %8.5f",k,p[k]);
                   12304:     printf("\n");
                   12305:     
                   12306:     /*--------- results files --------------*/
1.283     brouard  12307:     /* 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  12308:     
                   12309:     
                   12310:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12311:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12312:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12313:     for(i=1,jk=1; i <=nlstate; i++){
                   12314:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12315:        if (k != i) {
                   12316:          printf("%d%d ",i,k);
                   12317:          fprintf(ficlog,"%d%d ",i,k);
                   12318:          fprintf(ficres,"%1d%1d ",i,k);
                   12319:          for(j=1; j <=ncovmodel; j++){
                   12320:            printf("%12.7f ",p[jk]);
                   12321:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12322:            fprintf(ficres,"%12.7f ",p[jk]);
                   12323:            jk++; 
                   12324:          }
                   12325:          printf("\n");
                   12326:          fprintf(ficlog,"\n");
                   12327:          fprintf(ficres,"\n");
                   12328:        }
1.126     brouard  12329:       }
                   12330:     }
1.203     brouard  12331:     if(mle != 0){
                   12332:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12333:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12334:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12335:       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");
                   12336:       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");
                   12337:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12338:        for(k=1; k <=(nlstate+ndeath); k++){
                   12339:          if (k != i) {
                   12340:            printf("%d%d ",i,k);
                   12341:            fprintf(ficlog,"%d%d ",i,k);
                   12342:            for(j=1; j <=ncovmodel; j++){
                   12343:              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]));
                   12344:              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]));
                   12345:              jk++; 
                   12346:            }
                   12347:            printf("\n");
                   12348:            fprintf(ficlog,"\n");
                   12349:          }
                   12350:        }
1.193     brouard  12351:       }
1.203     brouard  12352:     } /* end of hesscov and Wald tests */
1.225     brouard  12353:     
1.203     brouard  12354:     /*  */
1.126     brouard  12355:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12356:     printf("# Scales (for hessian or gradient estimation)\n");
                   12357:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12358:     for(i=1,jk=1; i <=nlstate; i++){
                   12359:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12360:        if (j!=i) {
                   12361:          fprintf(ficres,"%1d%1d",i,j);
                   12362:          printf("%1d%1d",i,j);
                   12363:          fprintf(ficlog,"%1d%1d",i,j);
                   12364:          for(k=1; k<=ncovmodel;k++){
                   12365:            printf(" %.5e",delti[jk]);
                   12366:            fprintf(ficlog," %.5e",delti[jk]);
                   12367:            fprintf(ficres," %.5e",delti[jk]);
                   12368:            jk++;
                   12369:          }
                   12370:          printf("\n");
                   12371:          fprintf(ficlog,"\n");
                   12372:          fprintf(ficres,"\n");
                   12373:        }
1.126     brouard  12374:       }
                   12375:     }
                   12376:     
                   12377:     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  12378:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12379:       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");
                   12380:     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");
                   12381:     /* # 121 Var(a12)\n\ */
                   12382:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12383:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12384:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12385:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12386:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12387:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12388:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12389:     
                   12390:     
                   12391:     /* Just to have a covariance matrix which will be more understandable
                   12392:        even is we still don't want to manage dictionary of variables
                   12393:     */
                   12394:     for(itimes=1;itimes<=2;itimes++){
                   12395:       jj=0;
                   12396:       for(i=1; i <=nlstate; i++){
1.225     brouard  12397:        for(j=1; j <=nlstate+ndeath; j++){
                   12398:          if(j==i) continue;
                   12399:          for(k=1; k<=ncovmodel;k++){
                   12400:            jj++;
                   12401:            ca[0]= k+'a'-1;ca[1]='\0';
                   12402:            if(itimes==1){
                   12403:              if(mle>=1)
                   12404:                printf("#%1d%1d%d",i,j,k);
                   12405:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12406:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12407:            }else{
                   12408:              if(mle>=1)
                   12409:                printf("%1d%1d%d",i,j,k);
                   12410:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12411:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12412:            }
                   12413:            ll=0;
                   12414:            for(li=1;li <=nlstate; li++){
                   12415:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12416:                if(lj==li) continue;
                   12417:                for(lk=1;lk<=ncovmodel;lk++){
                   12418:                  ll++;
                   12419:                  if(ll<=jj){
                   12420:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12421:                    if(ll<jj){
                   12422:                      if(itimes==1){
                   12423:                        if(mle>=1)
                   12424:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12425:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12426:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12427:                      }else{
                   12428:                        if(mle>=1)
                   12429:                          printf(" %.5e",matcov[jj][ll]); 
                   12430:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12431:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12432:                      }
                   12433:                    }else{
                   12434:                      if(itimes==1){
                   12435:                        if(mle>=1)
                   12436:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12437:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12438:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12439:                      }else{
                   12440:                        if(mle>=1)
                   12441:                          printf(" %.7e",matcov[jj][ll]); 
                   12442:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12443:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12444:                      }
                   12445:                    }
                   12446:                  }
                   12447:                } /* end lk */
                   12448:              } /* end lj */
                   12449:            } /* end li */
                   12450:            if(mle>=1)
                   12451:              printf("\n");
                   12452:            fprintf(ficlog,"\n");
                   12453:            fprintf(ficres,"\n");
                   12454:            numlinepar++;
                   12455:          } /* end k*/
                   12456:        } /*end j */
1.126     brouard  12457:       } /* end i */
                   12458:     } /* end itimes */
                   12459:     
                   12460:     fflush(ficlog);
                   12461:     fflush(ficres);
1.225     brouard  12462:     while(fgets(line, MAXLINE, ficpar)) {
                   12463:       /* If line starts with a # it is a comment */
                   12464:       if (line[0] == '#') {
                   12465:        numlinepar++;
                   12466:        fputs(line,stdout);
                   12467:        fputs(line,ficparo);
                   12468:        fputs(line,ficlog);
1.299     brouard  12469:        fputs(line,ficres);
1.225     brouard  12470:        continue;
                   12471:       }else
                   12472:        break;
                   12473:     }
                   12474:     
1.209     brouard  12475:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12476:     /*   ungetc(c,ficpar); */
                   12477:     /*   fgets(line, MAXLINE, ficpar); */
                   12478:     /*   fputs(line,stdout); */
                   12479:     /*   fputs(line,ficparo); */
                   12480:     /* } */
                   12481:     /* ungetc(c,ficpar); */
1.126     brouard  12482:     
                   12483:     estepm=0;
1.209     brouard  12484:     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  12485:       
                   12486:       if (num_filled != 6) {
                   12487:        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);
                   12488:        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);
                   12489:        goto end;
                   12490:       }
                   12491:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12492:     }
                   12493:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12494:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12495:     
1.209     brouard  12496:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12497:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12498:     if (fage <= 2) {
                   12499:       bage = ageminpar;
                   12500:       fage = agemaxpar;
                   12501:     }
                   12502:     
                   12503:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12504:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12505:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12506:                
1.186     brouard  12507:     /* Other stuffs, more or less useful */    
1.254     brouard  12508:     while(fgets(line, MAXLINE, ficpar)) {
                   12509:       /* If line starts with a # it is a comment */
                   12510:       if (line[0] == '#') {
                   12511:        numlinepar++;
                   12512:        fputs(line,stdout);
                   12513:        fputs(line,ficparo);
                   12514:        fputs(line,ficlog);
1.299     brouard  12515:        fputs(line,ficres);
1.254     brouard  12516:        continue;
                   12517:       }else
                   12518:        break;
                   12519:     }
                   12520: 
                   12521:     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){
                   12522:       
                   12523:       if (num_filled != 7) {
                   12524:        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);
                   12525:        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);
                   12526:        goto end;
                   12527:       }
                   12528:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12529:       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);
                   12530:       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);
                   12531:       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  12532:     }
1.254     brouard  12533: 
                   12534:     while(fgets(line, MAXLINE, ficpar)) {
                   12535:       /* If line starts with a # it is a comment */
                   12536:       if (line[0] == '#') {
                   12537:        numlinepar++;
                   12538:        fputs(line,stdout);
                   12539:        fputs(line,ficparo);
                   12540:        fputs(line,ficlog);
1.299     brouard  12541:        fputs(line,ficres);
1.254     brouard  12542:        continue;
                   12543:       }else
                   12544:        break;
1.126     brouard  12545:     }
                   12546:     
                   12547:     
                   12548:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12549:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12550:     
1.254     brouard  12551:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12552:       if (num_filled != 1) {
                   12553:        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);
                   12554:        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);
                   12555:        goto end;
                   12556:       }
                   12557:       printf("pop_based=%d\n",popbased);
                   12558:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12559:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12560:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12561:     }
                   12562:      
1.258     brouard  12563:     /* Results */
1.307     brouard  12564:     endishere=0;
1.258     brouard  12565:     nresult=0;
1.308     brouard  12566:     parameterline=0;
1.258     brouard  12567:     do{
                   12568:       if(!fgets(line, MAXLINE, ficpar)){
                   12569:        endishere=1;
1.308     brouard  12570:        parameterline=15;
1.258     brouard  12571:       }else if (line[0] == '#') {
                   12572:        /* If line starts with a # it is a comment */
1.254     brouard  12573:        numlinepar++;
                   12574:        fputs(line,stdout);
                   12575:        fputs(line,ficparo);
                   12576:        fputs(line,ficlog);
1.299     brouard  12577:        fputs(line,ficres);
1.254     brouard  12578:        continue;
1.258     brouard  12579:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12580:        parameterline=11;
1.296     brouard  12581:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12582:        parameterline=12;
1.307     brouard  12583:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  12584:        parameterline=13;
1.307     brouard  12585:       }
1.258     brouard  12586:       else{
                   12587:        parameterline=14;
1.254     brouard  12588:       }
1.308     brouard  12589:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  12590:       case 11:
1.296     brouard  12591:        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)){
                   12592:                  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  12593:          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);
                   12594:          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);
                   12595:          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);
                   12596:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12597:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12598:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12599:           prvforecast = 1;
                   12600:        } 
                   12601:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  12602:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12603:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12604:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12605:           prvforecast = 2;
                   12606:        }
                   12607:        else {
                   12608:          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);
                   12609:          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);
                   12610:          goto end;
1.258     brouard  12611:        }
1.254     brouard  12612:        break;
1.258     brouard  12613:       case 12:
1.296     brouard  12614:        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)){
                   12615:           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);
                   12616:          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);
                   12617:          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);
                   12618:          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);
                   12619:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12620:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12621:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12622:           prvbackcast = 1;
                   12623:        } 
                   12624:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  12625:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12626:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12627:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12628:           prvbackcast = 2;
                   12629:        }
                   12630:        else {
                   12631:          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);
                   12632:          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);
                   12633:          goto end;
1.258     brouard  12634:        }
1.230     brouard  12635:        break;
1.258     brouard  12636:       case 13:
1.307     brouard  12637:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   12638:        nresult++; /* Sum of resultlines */
                   12639:        printf("Result %d: result:%s\n",nresult, resultline);
                   12640:        if(nresult > MAXRESULTLINES){
                   12641:          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);
                   12642:          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);
                   12643:          goto end;
                   12644:        }
1.310     brouard  12645:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  12646:          fprintf(ficparo,"result: %s\n",resultline);
                   12647:          fprintf(ficres,"result: %s\n",resultline);
                   12648:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  12649:        } else
                   12650:          goto end;
1.307     brouard  12651:        break;
                   12652:       case 14:
                   12653:        printf("Error: Unknown command '%s'\n",line);
                   12654:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  12655:        if(line[0] == ' ' || line[0] == '\n'){
                   12656:          printf("It should not be an empty line '%s'\n",line);
                   12657:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   12658:        }         
1.307     brouard  12659:        if(ncovmodel >=2 && nresult==0 ){
                   12660:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   12661:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12662:        }
1.307     brouard  12663:        /* goto end; */
                   12664:        break;
1.308     brouard  12665:       case 15:
                   12666:        printf("End of resultlines.\n");
                   12667:        fprintf(ficlog,"End of resultlines.\n");
                   12668:        break;
                   12669:       default: /* parameterline =0 */
1.307     brouard  12670:        nresult=1;
                   12671:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  12672:       } /* End switch parameterline */
                   12673:     }while(endishere==0); /* End do */
1.126     brouard  12674:     
1.230     brouard  12675:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12676:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12677:     
                   12678:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12679:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12680:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12681: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12682: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12683:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12684: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12685: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12686:     }else{
1.270     brouard  12687:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12688:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12689:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12690:       if(prvforecast==1){
                   12691:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12692:         jprojd=jproj1;
                   12693:         mprojd=mproj1;
                   12694:         anprojd=anproj1;
                   12695:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12696:         jprojf=jproj2;
                   12697:         mprojf=mproj2;
                   12698:         anprojf=anproj2;
                   12699:       } else if(prvforecast == 2){
                   12700:         dateprojd=dateintmean;
                   12701:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12702:         dateprojf=dateintmean+yrfproj;
                   12703:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12704:       }
                   12705:       if(prvbackcast==1){
                   12706:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12707:         jbackd=jback1;
                   12708:         mbackd=mback1;
                   12709:         anbackd=anback1;
                   12710:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12711:         jbackf=jback2;
                   12712:         mbackf=mback2;
                   12713:         anbackf=anback2;
                   12714:       } else if(prvbackcast == 2){
                   12715:         datebackd=dateintmean;
                   12716:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12717:         datebackf=dateintmean-yrbproj;
                   12718:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12719:       }
                   12720:       
                   12721:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12722:     }
                   12723:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12724:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12725:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12726:                
1.225     brouard  12727:     /*------------ free_vector  -------------*/
                   12728:     /*  chdir(path); */
1.220     brouard  12729:                
1.215     brouard  12730:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12731:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12732:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12733:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12734:     free_lvector(num,firstobs,lastobs);
                   12735:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12736:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12737:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12738:     fclose(ficparo);
                   12739:     fclose(ficres);
1.220     brouard  12740:                
                   12741:                
1.186     brouard  12742:     /* Other results (useful)*/
1.220     brouard  12743:                
                   12744:                
1.126     brouard  12745:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12746:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12747:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12748:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12749:     fclose(ficrespl);
                   12750: 
                   12751:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12752:     /*#include "hpijx.h"*/
                   12753:     hPijx(p, bage, fage);
1.145     brouard  12754:     fclose(ficrespij);
1.227     brouard  12755:     
1.220     brouard  12756:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12757:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12758:     k=1;
1.126     brouard  12759:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12760:     
1.269     brouard  12761:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12762:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12763:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12764:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12765:        for(k=1;k<=ncovcombmax;k++)
                   12766:          probs[i][j][k]=0.;
1.269     brouard  12767:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12768:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12769:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12770:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12771:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12772:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12773:          for(k=1;k<=ncovcombmax;k++)
                   12774:            mobaverages[i][j][k]=0.;
1.219     brouard  12775:       mobaverage=mobaverages;
                   12776:       if (mobilav!=0) {
1.235     brouard  12777:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12778:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12779:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12780:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12781:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12782:        }
1.269     brouard  12783:       } else if (mobilavproj !=0) {
1.235     brouard  12784:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12785:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12786:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12787:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12788:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12789:        }
1.269     brouard  12790:       }else{
                   12791:        printf("Internal error moving average\n");
                   12792:        fflush(stdout);
                   12793:        exit(1);
1.219     brouard  12794:       }
                   12795:     }/* end if moving average */
1.227     brouard  12796:     
1.126     brouard  12797:     /*---------- Forecasting ------------------*/
1.296     brouard  12798:     if(prevfcast==1){ 
                   12799:       /*   /\*    if(stepm ==1){*\/ */
                   12800:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12801:       /*This done previously after freqsummary.*/
                   12802:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   12803:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   12804:       
                   12805:       /* } else if (prvforecast==2){ */
                   12806:       /*   /\*    if(stepm ==1){*\/ */
                   12807:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12808:       /* } */
                   12809:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   12810:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  12811:     }
1.269     brouard  12812: 
1.296     brouard  12813:     /* Prevbcasting */
                   12814:     if(prevbcast==1){
1.219     brouard  12815:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12816:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12817:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12818: 
                   12819:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12820: 
                   12821:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12822: 
1.219     brouard  12823:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12824:       fclose(ficresplb);
                   12825: 
1.222     brouard  12826:       hBijx(p, bage, fage, mobaverage);
                   12827:       fclose(ficrespijb);
1.219     brouard  12828: 
1.296     brouard  12829:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   12830:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   12831:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   12832:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   12833:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   12834:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   12835: 
                   12836:       
1.269     brouard  12837:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12838: 
                   12839:       
1.269     brouard  12840:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12841:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12842:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12843:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  12844:     }    /* end  Prevbcasting */
1.268     brouard  12845:  
1.186     brouard  12846:  
                   12847:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12848: 
1.215     brouard  12849:     free_ivector(wav,1,imx);
                   12850:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12851:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12852:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12853:                
                   12854:                
1.127     brouard  12855:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12856:                
1.201     brouard  12857:     strcpy(filerese,"E_");
                   12858:     strcat(filerese,fileresu);
1.126     brouard  12859:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12860:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12861:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12862:     }
1.208     brouard  12863:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12864:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12865: 
                   12866:     pstamp(ficreseij);
1.219     brouard  12867:                
1.235     brouard  12868:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12869:     if (cptcovn < 1){i1=1;}
                   12870:     
                   12871:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12872:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12873:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12874:        continue;
1.219     brouard  12875:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12876:       printf("\n#****** ");
1.225     brouard  12877:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12878:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12879:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12880:       }
                   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(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12884:       }
                   12885:       fprintf(ficreseij,"******\n");
1.235     brouard  12886:       printf("******\n");
1.219     brouard  12887:       
                   12888:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12889:       oldm=oldms;savm=savms;
1.235     brouard  12890:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12891:       
1.219     brouard  12892:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12893:     }
                   12894:     fclose(ficreseij);
1.208     brouard  12895:     printf("done evsij\n");fflush(stdout);
                   12896:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12897: 
1.218     brouard  12898:                
1.227     brouard  12899:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12900:                
1.201     brouard  12901:     strcpy(filerest,"T_");
                   12902:     strcat(filerest,fileresu);
1.127     brouard  12903:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12904:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12905:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12906:     }
1.208     brouard  12907:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12908:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12909:     strcpy(fileresstde,"STDE_");
                   12910:     strcat(fileresstde,fileresu);
1.126     brouard  12911:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12912:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12913:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12914:     }
1.227     brouard  12915:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12916:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12917: 
1.201     brouard  12918:     strcpy(filerescve,"CVE_");
                   12919:     strcat(filerescve,fileresu);
1.126     brouard  12920:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12921:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12922:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12923:     }
1.227     brouard  12924:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12925:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12926: 
1.201     brouard  12927:     strcpy(fileresv,"V_");
                   12928:     strcat(fileresv,fileresu);
1.126     brouard  12929:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12930:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12931:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12932:     }
1.227     brouard  12933:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12934:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12935: 
1.235     brouard  12936:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12937:     if (cptcovn < 1){i1=1;}
                   12938:     
                   12939:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12940:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12941:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12942:        continue;
1.242     brouard  12943:       printf("\n#****** Result for:");
                   12944:       fprintf(ficrest,"\n#****** Result for:");
                   12945:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12946:       for(j=1;j<=cptcoveff;j++){ 
                   12947:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12948:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12949:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12950:       }
1.235     brouard  12951:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12952:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12953:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12954:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12955:       }        
1.208     brouard  12956:       fprintf(ficrest,"******\n");
1.227     brouard  12957:       fprintf(ficlog,"******\n");
                   12958:       printf("******\n");
1.208     brouard  12959:       
                   12960:       fprintf(ficresstdeij,"\n#****** ");
                   12961:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12962:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12963:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12964:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12965:       }
1.235     brouard  12966:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12967:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12968:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12969:       }        
1.208     brouard  12970:       fprintf(ficresstdeij,"******\n");
                   12971:       fprintf(ficrescveij,"******\n");
                   12972:       
                   12973:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12974:       /* pstamp(ficresvij); */
1.225     brouard  12975:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12976:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12977:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12978:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12979:       }        
1.208     brouard  12980:       fprintf(ficresvij,"******\n");
                   12981:       
                   12982:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12983:       oldm=oldms;savm=savms;
1.235     brouard  12984:       printf(" cvevsij ");
                   12985:       fprintf(ficlog, " cvevsij ");
                   12986:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12987:       printf(" end cvevsij \n ");
                   12988:       fprintf(ficlog, " end cvevsij \n ");
                   12989:       
                   12990:       /*
                   12991:        */
                   12992:       /* goto endfree; */
                   12993:       
                   12994:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12995:       pstamp(ficrest);
                   12996:       
1.269     brouard  12997:       epj=vector(1,nlstate+1);
1.208     brouard  12998:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12999:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13000:        cptcod= 0; /* To be deleted */
                   13001:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13002:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13003:        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  13004:        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 ");
                   13005:        if(vpopbased==1)
                   13006:          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);
                   13007:        else
1.288     brouard  13008:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13009:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13010:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13011:        fprintf(ficrest,"\n");
                   13012:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13013:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13014:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13015:        for(age=bage; age <=fage ;age++){
1.235     brouard  13016:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13017:          if (vpopbased==1) {
                   13018:            if(mobilav ==0){
                   13019:              for(i=1; i<=nlstate;i++)
                   13020:                prlim[i][i]=probs[(int)age][i][k];
                   13021:            }else{ /* mobilav */ 
                   13022:              for(i=1; i<=nlstate;i++)
                   13023:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13024:            }
                   13025:          }
1.219     brouard  13026:          
1.227     brouard  13027:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13028:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13029:          /* printf(" age %4.0f ",age); */
                   13030:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13031:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13032:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13033:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13034:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13035:            }
                   13036:            epj[nlstate+1] +=epj[j];
                   13037:          }
                   13038:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13039:          
1.227     brouard  13040:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13041:            for(j=1;j <=nlstate;j++)
                   13042:              vepp += vareij[i][j][(int)age];
                   13043:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13044:          for(j=1;j <=nlstate;j++){
                   13045:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13046:          }
                   13047:          fprintf(ficrest,"\n");
                   13048:        }
1.208     brouard  13049:       } /* End vpopbased */
1.269     brouard  13050:       free_vector(epj,1,nlstate+1);
1.208     brouard  13051:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13052:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13053:       printf("done selection\n");fflush(stdout);
                   13054:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13055:       
1.235     brouard  13056:     } /* End k selection */
1.227     brouard  13057: 
                   13058:     printf("done State-specific expectancies\n");fflush(stdout);
                   13059:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13060: 
1.288     brouard  13061:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13062:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13063: 
1.227     brouard  13064:     
1.290     brouard  13065:     free_vector(weight,firstobs,lastobs);
1.227     brouard  13066:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13067:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13068:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13069:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13070:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13071:     free_ivector(tab,1,NCOVMAX);
                   13072:     fclose(ficresstdeij);
                   13073:     fclose(ficrescveij);
                   13074:     fclose(ficresvij);
                   13075:     fclose(ficrest);
                   13076:     fclose(ficpar);
                   13077:     
                   13078:     
1.126     brouard  13079:     /*---------- End : free ----------------*/
1.219     brouard  13080:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13081:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13082:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13083:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13084:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13085:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13086:   /* endfree:*/
                   13087:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13088:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13089:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13090:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13091:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13092:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13093:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13094:   free_matrix(matcov,1,npar,1,npar);
                   13095:   free_matrix(hess,1,npar,1,npar);
                   13096:   /*free_vector(delti,1,npar);*/
                   13097:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13098:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13099:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13100:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13101:   
                   13102:   free_ivector(ncodemax,1,NCOVMAX);
                   13103:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13104:   free_ivector(Dummy,-1,NCOVMAX);
                   13105:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13106:   free_ivector(DummyV,1,NCOVMAX);
                   13107:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13108:   free_ivector(Typevar,-1,NCOVMAX);
                   13109:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13110:   free_ivector(TvarsQ,1,NCOVMAX);
                   13111:   free_ivector(TvarsQind,1,NCOVMAX);
                   13112:   free_ivector(TvarsD,1,NCOVMAX);
                   13113:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13114:   free_ivector(TvarFD,1,NCOVMAX);
                   13115:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13116:   free_ivector(TvarF,1,NCOVMAX);
                   13117:   free_ivector(TvarFind,1,NCOVMAX);
                   13118:   free_ivector(TvarV,1,NCOVMAX);
                   13119:   free_ivector(TvarVind,1,NCOVMAX);
                   13120:   free_ivector(TvarA,1,NCOVMAX);
                   13121:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13122:   free_ivector(TvarFQ,1,NCOVMAX);
                   13123:   free_ivector(TvarFQind,1,NCOVMAX);
                   13124:   free_ivector(TvarVD,1,NCOVMAX);
                   13125:   free_ivector(TvarVDind,1,NCOVMAX);
                   13126:   free_ivector(TvarVQ,1,NCOVMAX);
                   13127:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13128:   free_ivector(Tvarsel,1,NCOVMAX);
                   13129:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13130:   free_ivector(Tposprod,1,NCOVMAX);
                   13131:   free_ivector(Tprod,1,NCOVMAX);
                   13132:   free_ivector(Tvaraff,1,NCOVMAX);
                   13133:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13134:   free_ivector(Tage,1,NCOVMAX);
                   13135:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13136:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13137:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13138:   
                   13139:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13140:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13141:   fflush(fichtm);
                   13142:   fflush(ficgp);
                   13143:   
1.227     brouard  13144:   
1.126     brouard  13145:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13146:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13147:     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  13148:   }else{
                   13149:     printf("End of Imach\n");
                   13150:     fprintf(ficlog,"End of Imach\n");
                   13151:   }
                   13152:   printf("See log file on %s\n",filelog);
                   13153:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13154:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13155:   rend_time = time(NULL);  
                   13156:   end_time = *localtime(&rend_time);
                   13157:   /* tml = *localtime(&end_time.tm_sec); */
                   13158:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13159:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13160:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13161:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13162:   
1.157     brouard  13163:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13164:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13165:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13166:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13167: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13168:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13169:   fclose(fichtm);
                   13170:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13171:   fclose(fichtmcov);
                   13172:   fclose(ficgp);
                   13173:   fclose(ficlog);
                   13174:   /*------ End -----------*/
1.227     brouard  13175:   
1.281     brouard  13176: 
                   13177: /* Executes gnuplot */
1.227     brouard  13178:   
                   13179:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13180: #ifdef WIN32
1.227     brouard  13181:   if (_chdir(pathcd) != 0)
                   13182:     printf("Can't move to directory %s!\n",path);
                   13183:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13184: #else
1.227     brouard  13185:     if(chdir(pathcd) != 0)
                   13186:       printf("Can't move to directory %s!\n", path);
                   13187:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13188: #endif 
1.126     brouard  13189:     printf("Current directory %s!\n",pathcd);
                   13190:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13191:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13192: #ifdef _WIN32
1.126     brouard  13193:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13194: #endif
                   13195:   if(!stat(plotcmd,&info)){
1.158     brouard  13196:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13197:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13198:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13199:     }else
                   13200:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13201: #ifdef __unix
1.126     brouard  13202:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13203:     if(!stat(plotcmd,&info)){
1.158     brouard  13204:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13205:     }else
                   13206:       strcpy(pplotcmd,plotcmd);
                   13207: #endif
                   13208:   }else
                   13209:     strcpy(pplotcmd,plotcmd);
                   13210:   
                   13211:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13212:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13213:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13214:   
1.126     brouard  13215:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13216:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13217:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13218:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13219:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13220:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13221:       strcpy(plotcmd,pplotcmd);
                   13222:     }
1.126     brouard  13223:   }
1.158     brouard  13224:   printf(" Successful, please wait...");
1.126     brouard  13225:   while (z[0] != 'q') {
                   13226:     /* chdir(path); */
1.154     brouard  13227:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13228:     scanf("%s",z);
                   13229: /*     if (z[0] == 'c') system("./imach"); */
                   13230:     if (z[0] == 'e') {
1.158     brouard  13231: #ifdef __APPLE__
1.152     brouard  13232:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13233: #elif __linux
                   13234:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13235: #else
1.152     brouard  13236:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13237: #endif
                   13238:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13239:       system(pplotcmd);
1.126     brouard  13240:     }
                   13241:     else if (z[0] == 'g') system(plotcmd);
                   13242:     else if (z[0] == 'q') exit(0);
                   13243:   }
1.227     brouard  13244: end:
1.126     brouard  13245:   while (z[0] != 'q') {
1.195     brouard  13246:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13247:     scanf("%s",z);
                   13248:   }
1.283     brouard  13249:   printf("End\n");
1.282     brouard  13250:   exit(0);
1.126     brouard  13251: }

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