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

1.303   ! brouard     1: /* $Id: imach.c,v 1.302 2020/02/22 21:00:05 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.303   ! brouard     4:   Revision 1.302  2020/02/22 21:00:05  brouard
        !             5:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
        !             6:   and life table from the data without any state)
        !             7: 
1.302     brouard     8:   Revision 1.301  2019/06/04 13:51:20  brouard
                      9:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                     10: 
1.301     brouard    11:   Revision 1.300  2019/05/22 19:09:45  brouard
                     12:   Summary: version 0.99r19 of May 2019
                     13: 
1.300     brouard    14:   Revision 1.299  2019/05/22 18:37:08  brouard
                     15:   Summary: Cleaned 0.99r19
                     16: 
1.299     brouard    17:   Revision 1.298  2019/05/22 18:19:56  brouard
                     18:   *** empty log message ***
                     19: 
1.298     brouard    20:   Revision 1.297  2019/05/22 17:56:10  brouard
                     21:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                     22: 
1.297     brouard    23:   Revision 1.296  2019/05/20 13:03:18  brouard
                     24:   Summary: Projection syntax simplified
                     25: 
                     26: 
                     27:   We can now start projections, forward or backward, from the mean date
                     28:   of inteviews up to or down to a number of years of projection:
                     29:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                     30:   or
                     31:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                     32:   or
                     33:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                     34:   or
                     35:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                     36: 
1.296     brouard    37:   Revision 1.295  2019/05/18 09:52:50  brouard
                     38:   Summary: doxygen tex bug
                     39: 
1.295     brouard    40:   Revision 1.294  2019/05/16 14:54:33  brouard
                     41:   Summary: There was some wrong lines added
                     42: 
1.294     brouard    43:   Revision 1.293  2019/05/09 15:17:34  brouard
                     44:   *** empty log message ***
                     45: 
1.293     brouard    46:   Revision 1.292  2019/05/09 14:17:20  brouard
                     47:   Summary: Some updates
                     48: 
1.292     brouard    49:   Revision 1.291  2019/05/09 13:44:18  brouard
                     50:   Summary: Before ncovmax
                     51: 
1.291     brouard    52:   Revision 1.290  2019/05/09 13:39:37  brouard
                     53:   Summary: 0.99r18 unlimited number of individuals
                     54: 
                     55:   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.
                     56: 
1.290     brouard    57:   Revision 1.289  2018/12/13 09:16:26  brouard
                     58:   Summary: Bug for young ages (<-30) will be in r17
                     59: 
1.289     brouard    60:   Revision 1.288  2018/05/02 20:58:27  brouard
                     61:   Summary: Some bugs fixed
                     62: 
1.288     brouard    63:   Revision 1.287  2018/05/01 17:57:25  brouard
                     64:   Summary: Bug fixed by providing frequencies only for non missing covariates
                     65: 
1.287     brouard    66:   Revision 1.286  2018/04/27 14:27:04  brouard
                     67:   Summary: some minor bugs
                     68: 
1.286     brouard    69:   Revision 1.285  2018/04/21 21:02:16  brouard
                     70:   Summary: Some bugs fixed, valgrind tested
                     71: 
1.285     brouard    72:   Revision 1.284  2018/04/20 05:22:13  brouard
                     73:   Summary: Computing mean and stdeviation of fixed quantitative variables
                     74: 
1.284     brouard    75:   Revision 1.283  2018/04/19 14:49:16  brouard
                     76:   Summary: Some minor bugs fixed
                     77: 
1.283     brouard    78:   Revision 1.282  2018/02/27 22:50:02  brouard
                     79:   *** empty log message ***
                     80: 
1.282     brouard    81:   Revision 1.281  2018/02/27 19:25:23  brouard
                     82:   Summary: Adding second argument for quitting
                     83: 
1.281     brouard    84:   Revision 1.280  2018/02/21 07:58:13  brouard
                     85:   Summary: 0.99r15
                     86: 
                     87:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                     88: 
1.280     brouard    89:   Revision 1.279  2017/07/20 13:35:01  brouard
                     90:   Summary: temporary working
                     91: 
1.279     brouard    92:   Revision 1.278  2017/07/19 14:09:02  brouard
                     93:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                     94: 
1.278     brouard    95:   Revision 1.277  2017/07/17 08:53:49  brouard
                     96:   Summary: BOM files can be read now
                     97: 
1.277     brouard    98:   Revision 1.276  2017/06/30 15:48:31  brouard
                     99:   Summary: Graphs improvements
                    100: 
1.276     brouard   101:   Revision 1.275  2017/06/30 13:39:33  brouard
                    102:   Summary: Saito's color
                    103: 
1.275     brouard   104:   Revision 1.274  2017/06/29 09:47:08  brouard
                    105:   Summary: Version 0.99r14
                    106: 
1.274     brouard   107:   Revision 1.273  2017/06/27 11:06:02  brouard
                    108:   Summary: More documentation on projections
                    109: 
1.273     brouard   110:   Revision 1.272  2017/06/27 10:22:40  brouard
                    111:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    112: 
1.272     brouard   113:   Revision 1.271  2017/06/27 10:17:50  brouard
                    114:   Summary: Some bug with rint
                    115: 
1.271     brouard   116:   Revision 1.270  2017/05/24 05:45:29  brouard
                    117:   *** empty log message ***
                    118: 
1.270     brouard   119:   Revision 1.269  2017/05/23 08:39:25  brouard
                    120:   Summary: Code into subroutine, cleanings
                    121: 
1.269     brouard   122:   Revision 1.268  2017/05/18 20:09:32  brouard
                    123:   Summary: backprojection and confidence intervals of backprevalence
                    124: 
1.268     brouard   125:   Revision 1.267  2017/05/13 10:25:05  brouard
                    126:   Summary: temporary save for backprojection
                    127: 
1.267     brouard   128:   Revision 1.266  2017/05/13 07:26:12  brouard
                    129:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    130: 
1.266     brouard   131:   Revision 1.265  2017/04/26 16:22:11  brouard
                    132:   Summary: imach 0.99r13 Some bugs fixed
                    133: 
1.265     brouard   134:   Revision 1.264  2017/04/26 06:01:29  brouard
                    135:   Summary: Labels in graphs
                    136: 
1.264     brouard   137:   Revision 1.263  2017/04/24 15:23:15  brouard
                    138:   Summary: to save
                    139: 
1.263     brouard   140:   Revision 1.262  2017/04/18 16:48:12  brouard
                    141:   *** empty log message ***
                    142: 
1.262     brouard   143:   Revision 1.261  2017/04/05 10:14:09  brouard
                    144:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    145: 
1.261     brouard   146:   Revision 1.260  2017/04/04 17:46:59  brouard
                    147:   Summary: Gnuplot indexations fixed (humm)
                    148: 
1.260     brouard   149:   Revision 1.259  2017/04/04 13:01:16  brouard
                    150:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    151: 
1.259     brouard   152:   Revision 1.258  2017/04/03 10:17:47  brouard
                    153:   Summary: Version 0.99r12
                    154: 
                    155:   Some cleanings, conformed with updated documentation.
                    156: 
1.258     brouard   157:   Revision 1.257  2017/03/29 16:53:30  brouard
                    158:   Summary: Temp
                    159: 
1.257     brouard   160:   Revision 1.256  2017/03/27 05:50:23  brouard
                    161:   Summary: Temporary
                    162: 
1.256     brouard   163:   Revision 1.255  2017/03/08 16:02:28  brouard
                    164:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    165: 
1.255     brouard   166:   Revision 1.254  2017/03/08 07:13:00  brouard
                    167:   Summary: Fixing data parameter line
                    168: 
1.254     brouard   169:   Revision 1.253  2016/12/15 11:59:41  brouard
                    170:   Summary: 0.99 in progress
                    171: 
1.253     brouard   172:   Revision 1.252  2016/09/15 21:15:37  brouard
                    173:   *** empty log message ***
                    174: 
1.252     brouard   175:   Revision 1.251  2016/09/15 15:01:13  brouard
                    176:   Summary: not working
                    177: 
1.251     brouard   178:   Revision 1.250  2016/09/08 16:07:27  brouard
                    179:   Summary: continue
                    180: 
1.250     brouard   181:   Revision 1.249  2016/09/07 17:14:18  brouard
                    182:   Summary: Starting values from frequencies
                    183: 
1.249     brouard   184:   Revision 1.248  2016/09/07 14:10:18  brouard
                    185:   *** empty log message ***
                    186: 
1.248     brouard   187:   Revision 1.247  2016/09/02 11:11:21  brouard
                    188:   *** empty log message ***
                    189: 
1.247     brouard   190:   Revision 1.246  2016/09/02 08:49:22  brouard
                    191:   *** empty log message ***
                    192: 
1.246     brouard   193:   Revision 1.245  2016/09/02 07:25:01  brouard
                    194:   *** empty log message ***
                    195: 
1.245     brouard   196:   Revision 1.244  2016/09/02 07:17:34  brouard
                    197:   *** empty log message ***
                    198: 
1.244     brouard   199:   Revision 1.243  2016/09/02 06:45:35  brouard
                    200:   *** empty log message ***
                    201: 
1.243     brouard   202:   Revision 1.242  2016/08/30 15:01:20  brouard
                    203:   Summary: Fixing a lots
                    204: 
1.242     brouard   205:   Revision 1.241  2016/08/29 17:17:25  brouard
                    206:   Summary: gnuplot problem in Back projection to fix
                    207: 
1.241     brouard   208:   Revision 1.240  2016/08/29 07:53:18  brouard
                    209:   Summary: Better
                    210: 
1.240     brouard   211:   Revision 1.239  2016/08/26 15:51:03  brouard
                    212:   Summary: Improvement in Powell output in order to copy and paste
                    213: 
                    214:   Author:
                    215: 
1.239     brouard   216:   Revision 1.238  2016/08/26 14:23:35  brouard
                    217:   Summary: Starting tests of 0.99
                    218: 
1.238     brouard   219:   Revision 1.237  2016/08/26 09:20:19  brouard
                    220:   Summary: to valgrind
                    221: 
1.237     brouard   222:   Revision 1.236  2016/08/25 10:50:18  brouard
                    223:   *** empty log message ***
                    224: 
1.236     brouard   225:   Revision 1.235  2016/08/25 06:59:23  brouard
                    226:   *** empty log message ***
                    227: 
1.235     brouard   228:   Revision 1.234  2016/08/23 16:51:20  brouard
                    229:   *** empty log message ***
                    230: 
1.234     brouard   231:   Revision 1.233  2016/08/23 07:40:50  brouard
                    232:   Summary: not working
                    233: 
1.233     brouard   234:   Revision 1.232  2016/08/22 14:20:21  brouard
                    235:   Summary: not working
                    236: 
1.232     brouard   237:   Revision 1.231  2016/08/22 07:17:15  brouard
                    238:   Summary: not working
                    239: 
1.231     brouard   240:   Revision 1.230  2016/08/22 06:55:53  brouard
                    241:   Summary: Not working
                    242: 
1.230     brouard   243:   Revision 1.229  2016/07/23 09:45:53  brouard
                    244:   Summary: Completing for func too
                    245: 
1.229     brouard   246:   Revision 1.228  2016/07/22 17:45:30  brouard
                    247:   Summary: Fixing some arrays, still debugging
                    248: 
1.227     brouard   249:   Revision 1.226  2016/07/12 18:42:34  brouard
                    250:   Summary: temp
                    251: 
1.226     brouard   252:   Revision 1.225  2016/07/12 08:40:03  brouard
                    253:   Summary: saving but not running
                    254: 
1.225     brouard   255:   Revision 1.224  2016/07/01 13:16:01  brouard
                    256:   Summary: Fixes
                    257: 
1.224     brouard   258:   Revision 1.223  2016/02/19 09:23:35  brouard
                    259:   Summary: temporary
                    260: 
1.223     brouard   261:   Revision 1.222  2016/02/17 08:14:50  brouard
                    262:   Summary: Probably last 0.98 stable version 0.98r6
                    263: 
1.222     brouard   264:   Revision 1.221  2016/02/15 23:35:36  brouard
                    265:   Summary: minor bug
                    266: 
1.220     brouard   267:   Revision 1.219  2016/02/15 00:48:12  brouard
                    268:   *** empty log message ***
                    269: 
1.219     brouard   270:   Revision 1.218  2016/02/12 11:29:23  brouard
                    271:   Summary: 0.99 Back projections
                    272: 
1.218     brouard   273:   Revision 1.217  2015/12/23 17:18:31  brouard
                    274:   Summary: Experimental backcast
                    275: 
1.217     brouard   276:   Revision 1.216  2015/12/18 17:32:11  brouard
                    277:   Summary: 0.98r4 Warning and status=-2
                    278: 
                    279:   Version 0.98r4 is now:
                    280:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    281:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    282:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    283: 
1.216     brouard   284:   Revision 1.215  2015/12/16 08:52:24  brouard
                    285:   Summary: 0.98r4 working
                    286: 
1.215     brouard   287:   Revision 1.214  2015/12/16 06:57:54  brouard
                    288:   Summary: temporary not working
                    289: 
1.214     brouard   290:   Revision 1.213  2015/12/11 18:22:17  brouard
                    291:   Summary: 0.98r4
                    292: 
1.213     brouard   293:   Revision 1.212  2015/11/21 12:47:24  brouard
                    294:   Summary: minor typo
                    295: 
1.212     brouard   296:   Revision 1.211  2015/11/21 12:41:11  brouard
                    297:   Summary: 0.98r3 with some graph of projected cross-sectional
                    298: 
                    299:   Author: Nicolas Brouard
                    300: 
1.211     brouard   301:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   302:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   303:   Summary: Adding ftolpl parameter
                    304:   Author: N Brouard
                    305: 
                    306:   We had difficulties to get smoothed confidence intervals. It was due
                    307:   to the period prevalence which wasn't computed accurately. The inner
                    308:   parameter ftolpl is now an outer parameter of the .imach parameter
                    309:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    310:   computation are long.
                    311: 
1.209     brouard   312:   Revision 1.208  2015/11/17 14:31:57  brouard
                    313:   Summary: temporary
                    314: 
1.208     brouard   315:   Revision 1.207  2015/10/27 17:36:57  brouard
                    316:   *** empty log message ***
                    317: 
1.207     brouard   318:   Revision 1.206  2015/10/24 07:14:11  brouard
                    319:   *** empty log message ***
                    320: 
1.206     brouard   321:   Revision 1.205  2015/10/23 15:50:53  brouard
                    322:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    323: 
1.205     brouard   324:   Revision 1.204  2015/10/01 16:20:26  brouard
                    325:   Summary: Some new graphs of contribution to likelihood
                    326: 
1.204     brouard   327:   Revision 1.203  2015/09/30 17:45:14  brouard
                    328:   Summary: looking at better estimation of the hessian
                    329: 
                    330:   Also a better criteria for convergence to the period prevalence And
                    331:   therefore adding the number of years needed to converge. (The
                    332:   prevalence in any alive state shold sum to one
                    333: 
1.203     brouard   334:   Revision 1.202  2015/09/22 19:45:16  brouard
                    335:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    336: 
1.202     brouard   337:   Revision 1.201  2015/09/15 17:34:58  brouard
                    338:   Summary: 0.98r0
                    339: 
                    340:   - Some new graphs like suvival functions
                    341:   - Some bugs fixed like model=1+age+V2.
                    342: 
1.201     brouard   343:   Revision 1.200  2015/09/09 16:53:55  brouard
                    344:   Summary: Big bug thanks to Flavia
                    345: 
                    346:   Even model=1+age+V2. did not work anymore
                    347: 
1.200     brouard   348:   Revision 1.199  2015/09/07 14:09:23  brouard
                    349:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    350: 
1.199     brouard   351:   Revision 1.198  2015/09/03 07:14:39  brouard
                    352:   Summary: 0.98q5 Flavia
                    353: 
1.198     brouard   354:   Revision 1.197  2015/09/01 18:24:39  brouard
                    355:   *** empty log message ***
                    356: 
1.197     brouard   357:   Revision 1.196  2015/08/18 23:17:52  brouard
                    358:   Summary: 0.98q5
                    359: 
1.196     brouard   360:   Revision 1.195  2015/08/18 16:28:39  brouard
                    361:   Summary: Adding a hack for testing purpose
                    362: 
                    363:   After reading the title, ftol and model lines, if the comment line has
                    364:   a q, starting with #q, the answer at the end of the run is quit. It
                    365:   permits to run test files in batch with ctest. The former workaround was
                    366:   $ echo q | imach foo.imach
                    367: 
1.195     brouard   368:   Revision 1.194  2015/08/18 13:32:00  brouard
                    369:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    370: 
1.194     brouard   371:   Revision 1.193  2015/08/04 07:17:42  brouard
                    372:   Summary: 0.98q4
                    373: 
1.193     brouard   374:   Revision 1.192  2015/07/16 16:49:02  brouard
                    375:   Summary: Fixing some outputs
                    376: 
1.192     brouard   377:   Revision 1.191  2015/07/14 10:00:33  brouard
                    378:   Summary: Some fixes
                    379: 
1.191     brouard   380:   Revision 1.190  2015/05/05 08:51:13  brouard
                    381:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    382: 
                    383:   Fix 1+age+.
                    384: 
1.190     brouard   385:   Revision 1.189  2015/04/30 14:45:16  brouard
                    386:   Summary: 0.98q2
                    387: 
1.189     brouard   388:   Revision 1.188  2015/04/30 08:27:53  brouard
                    389:   *** empty log message ***
                    390: 
1.188     brouard   391:   Revision 1.187  2015/04/29 09:11:15  brouard
                    392:   *** empty log message ***
                    393: 
1.187     brouard   394:   Revision 1.186  2015/04/23 12:01:52  brouard
                    395:   Summary: V1*age is working now, version 0.98q1
                    396: 
                    397:   Some codes had been disabled in order to simplify and Vn*age was
                    398:   working in the optimization phase, ie, giving correct MLE parameters,
                    399:   but, as usual, outputs were not correct and program core dumped.
                    400: 
1.186     brouard   401:   Revision 1.185  2015/03/11 13:26:42  brouard
                    402:   Summary: Inclusion of compile and links command line for Intel Compiler
                    403: 
1.185     brouard   404:   Revision 1.184  2015/03/11 11:52:39  brouard
                    405:   Summary: Back from Windows 8. Intel Compiler
                    406: 
1.184     brouard   407:   Revision 1.183  2015/03/10 20:34:32  brouard
                    408:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    409: 
                    410:   We use directest instead of original Powell test; probably no
                    411:   incidence on the results, but better justifications;
                    412:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    413:   wrong results.
                    414: 
1.183     brouard   415:   Revision 1.182  2015/02/12 08:19:57  brouard
                    416:   Summary: Trying to keep directest which seems simpler and more general
                    417:   Author: Nicolas Brouard
                    418: 
1.182     brouard   419:   Revision 1.181  2015/02/11 23:22:24  brouard
                    420:   Summary: Comments on Powell added
                    421: 
                    422:   Author:
                    423: 
1.181     brouard   424:   Revision 1.180  2015/02/11 17:33:45  brouard
                    425:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    426: 
1.180     brouard   427:   Revision 1.179  2015/01/04 09:57:06  brouard
                    428:   Summary: back to OS/X
                    429: 
1.179     brouard   430:   Revision 1.178  2015/01/04 09:35:48  brouard
                    431:   *** empty log message ***
                    432: 
1.178     brouard   433:   Revision 1.177  2015/01/03 18:40:56  brouard
                    434:   Summary: Still testing ilc32 on OSX
                    435: 
1.177     brouard   436:   Revision 1.176  2015/01/03 16:45:04  brouard
                    437:   *** empty log message ***
                    438: 
1.176     brouard   439:   Revision 1.175  2015/01/03 16:33:42  brouard
                    440:   *** empty log message ***
                    441: 
1.175     brouard   442:   Revision 1.174  2015/01/03 16:15:49  brouard
                    443:   Summary: Still in cross-compilation
                    444: 
1.174     brouard   445:   Revision 1.173  2015/01/03 12:06:26  brouard
                    446:   Summary: trying to detect cross-compilation
                    447: 
1.173     brouard   448:   Revision 1.172  2014/12/27 12:07:47  brouard
                    449:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    450: 
1.172     brouard   451:   Revision 1.171  2014/12/23 13:26:59  brouard
                    452:   Summary: Back from Visual C
                    453: 
                    454:   Still problem with utsname.h on Windows
                    455: 
1.171     brouard   456:   Revision 1.170  2014/12/23 11:17:12  brouard
                    457:   Summary: Cleaning some \%% back to %%
                    458: 
                    459:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    460: 
1.170     brouard   461:   Revision 1.169  2014/12/22 23:08:31  brouard
                    462:   Summary: 0.98p
                    463: 
                    464:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    465: 
1.169     brouard   466:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   467:   Summary: update
1.169     brouard   468: 
1.168     brouard   469:   Revision 1.167  2014/12/22 13:50:56  brouard
                    470:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    471: 
                    472:   Testing on Linux 64
                    473: 
1.167     brouard   474:   Revision 1.166  2014/12/22 11:40:47  brouard
                    475:   *** empty log message ***
                    476: 
1.166     brouard   477:   Revision 1.165  2014/12/16 11:20:36  brouard
                    478:   Summary: After compiling on Visual C
                    479: 
                    480:   * imach.c (Module): Merging 1.61 to 1.162
                    481: 
1.165     brouard   482:   Revision 1.164  2014/12/16 10:52:11  brouard
                    483:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    484: 
                    485:   * imach.c (Module): Merging 1.61 to 1.162
                    486: 
1.164     brouard   487:   Revision 1.163  2014/12/16 10:30:11  brouard
                    488:   * imach.c (Module): Merging 1.61 to 1.162
                    489: 
1.163     brouard   490:   Revision 1.162  2014/09/25 11:43:39  brouard
                    491:   Summary: temporary backup 0.99!
                    492: 
1.162     brouard   493:   Revision 1.1  2014/09/16 11:06:58  brouard
                    494:   Summary: With some code (wrong) for nlopt
                    495: 
                    496:   Author:
                    497: 
                    498:   Revision 1.161  2014/09/15 20:41:41  brouard
                    499:   Summary: Problem with macro SQR on Intel compiler
                    500: 
1.161     brouard   501:   Revision 1.160  2014/09/02 09:24:05  brouard
                    502:   *** empty log message ***
                    503: 
1.160     brouard   504:   Revision 1.159  2014/09/01 10:34:10  brouard
                    505:   Summary: WIN32
                    506:   Author: Brouard
                    507: 
1.159     brouard   508:   Revision 1.158  2014/08/27 17:11:51  brouard
                    509:   *** empty log message ***
                    510: 
1.158     brouard   511:   Revision 1.157  2014/08/27 16:26:55  brouard
                    512:   Summary: Preparing windows Visual studio version
                    513:   Author: Brouard
                    514: 
                    515:   In order to compile on Visual studio, time.h is now correct and time_t
                    516:   and tm struct should be used. difftime should be used but sometimes I
                    517:   just make the differences in raw time format (time(&now).
                    518:   Trying to suppress #ifdef LINUX
                    519:   Add xdg-open for __linux in order to open default browser.
                    520: 
1.157     brouard   521:   Revision 1.156  2014/08/25 20:10:10  brouard
                    522:   *** empty log message ***
                    523: 
1.156     brouard   524:   Revision 1.155  2014/08/25 18:32:34  brouard
                    525:   Summary: New compile, minor changes
                    526:   Author: Brouard
                    527: 
1.155     brouard   528:   Revision 1.154  2014/06/20 17:32:08  brouard
                    529:   Summary: Outputs now all graphs of convergence to period prevalence
                    530: 
1.154     brouard   531:   Revision 1.153  2014/06/20 16:45:46  brouard
                    532:   Summary: If 3 live state, convergence to period prevalence on same graph
                    533:   Author: Brouard
                    534: 
1.153     brouard   535:   Revision 1.152  2014/06/18 17:54:09  brouard
                    536:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    537: 
1.152     brouard   538:   Revision 1.151  2014/06/18 16:43:30  brouard
                    539:   *** empty log message ***
                    540: 
1.151     brouard   541:   Revision 1.150  2014/06/18 16:42:35  brouard
                    542:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    543:   Author: brouard
                    544: 
1.150     brouard   545:   Revision 1.149  2014/06/18 15:51:14  brouard
                    546:   Summary: Some fixes in parameter files errors
                    547:   Author: Nicolas Brouard
                    548: 
1.149     brouard   549:   Revision 1.148  2014/06/17 17:38:48  brouard
                    550:   Summary: Nothing new
                    551:   Author: Brouard
                    552: 
                    553:   Just a new packaging for OS/X version 0.98nS
                    554: 
1.148     brouard   555:   Revision 1.147  2014/06/16 10:33:11  brouard
                    556:   *** empty log message ***
                    557: 
1.147     brouard   558:   Revision 1.146  2014/06/16 10:20:28  brouard
                    559:   Summary: Merge
                    560:   Author: Brouard
                    561: 
                    562:   Merge, before building revised version.
                    563: 
1.146     brouard   564:   Revision 1.145  2014/06/10 21:23:15  brouard
                    565:   Summary: Debugging with valgrind
                    566:   Author: Nicolas Brouard
                    567: 
                    568:   Lot of changes in order to output the results with some covariates
                    569:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    570:   improve the code.
                    571:   No more memory valgrind error but a lot has to be done in order to
                    572:   continue the work of splitting the code into subroutines.
                    573:   Also, decodemodel has been improved. Tricode is still not
                    574:   optimal. nbcode should be improved. Documentation has been added in
                    575:   the source code.
                    576: 
1.144     brouard   577:   Revision 1.143  2014/01/26 09:45:38  brouard
                    578:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    579: 
                    580:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    581:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    582: 
1.143     brouard   583:   Revision 1.142  2014/01/26 03:57:36  brouard
                    584:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    585: 
                    586:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    587: 
1.142     brouard   588:   Revision 1.141  2014/01/26 02:42:01  brouard
                    589:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    590: 
1.141     brouard   591:   Revision 1.140  2011/09/02 10:37:54  brouard
                    592:   Summary: times.h is ok with mingw32 now.
                    593: 
1.140     brouard   594:   Revision 1.139  2010/06/14 07:50:17  brouard
                    595:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    596:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    597: 
1.139     brouard   598:   Revision 1.138  2010/04/30 18:19:40  brouard
                    599:   *** empty log message ***
                    600: 
1.138     brouard   601:   Revision 1.137  2010/04/29 18:11:38  brouard
                    602:   (Module): Checking covariates for more complex models
                    603:   than V1+V2. A lot of change to be done. Unstable.
                    604: 
1.137     brouard   605:   Revision 1.136  2010/04/26 20:30:53  brouard
                    606:   (Module): merging some libgsl code. Fixing computation
                    607:   of likelione (using inter/intrapolation if mle = 0) in order to
                    608:   get same likelihood as if mle=1.
                    609:   Some cleaning of code and comments added.
                    610: 
1.136     brouard   611:   Revision 1.135  2009/10/29 15:33:14  brouard
                    612:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    613: 
1.135     brouard   614:   Revision 1.134  2009/10/29 13:18:53  brouard
                    615:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    616: 
1.134     brouard   617:   Revision 1.133  2009/07/06 10:21:25  brouard
                    618:   just nforces
                    619: 
1.133     brouard   620:   Revision 1.132  2009/07/06 08:22:05  brouard
                    621:   Many tings
                    622: 
1.132     brouard   623:   Revision 1.131  2009/06/20 16:22:47  brouard
                    624:   Some dimensions resccaled
                    625: 
1.131     brouard   626:   Revision 1.130  2009/05/26 06:44:34  brouard
                    627:   (Module): Max Covariate is now set to 20 instead of 8. A
                    628:   lot of cleaning with variables initialized to 0. Trying to make
                    629:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    630: 
1.130     brouard   631:   Revision 1.129  2007/08/31 13:49:27  lievre
                    632:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    633: 
1.129     lievre    634:   Revision 1.128  2006/06/30 13:02:05  brouard
                    635:   (Module): Clarifications on computing e.j
                    636: 
1.128     brouard   637:   Revision 1.127  2006/04/28 18:11:50  brouard
                    638:   (Module): Yes the sum of survivors was wrong since
                    639:   imach-114 because nhstepm was no more computed in the age
                    640:   loop. Now we define nhstepma in the age loop.
                    641:   (Module): In order to speed up (in case of numerous covariates) we
                    642:   compute health expectancies (without variances) in a first step
                    643:   and then all the health expectancies with variances or standard
                    644:   deviation (needs data from the Hessian matrices) which slows the
                    645:   computation.
                    646:   In the future we should be able to stop the program is only health
                    647:   expectancies and graph are needed without standard deviations.
                    648: 
1.127     brouard   649:   Revision 1.126  2006/04/28 17:23:28  brouard
                    650:   (Module): Yes the sum of survivors was wrong since
                    651:   imach-114 because nhstepm was no more computed in the age
                    652:   loop. Now we define nhstepma in the age loop.
                    653:   Version 0.98h
                    654: 
1.126     brouard   655:   Revision 1.125  2006/04/04 15:20:31  lievre
                    656:   Errors in calculation of health expectancies. Age was not initialized.
                    657:   Forecasting file added.
                    658: 
                    659:   Revision 1.124  2006/03/22 17:13:53  lievre
                    660:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    661:   The log-likelihood is printed in the log file
                    662: 
                    663:   Revision 1.123  2006/03/20 10:52:43  brouard
                    664:   * imach.c (Module): <title> changed, corresponds to .htm file
                    665:   name. <head> headers where missing.
                    666: 
                    667:   * imach.c (Module): Weights can have a decimal point as for
                    668:   English (a comma might work with a correct LC_NUMERIC environment,
                    669:   otherwise the weight is truncated).
                    670:   Modification of warning when the covariates values are not 0 or
                    671:   1.
                    672:   Version 0.98g
                    673: 
                    674:   Revision 1.122  2006/03/20 09:45:41  brouard
                    675:   (Module): Weights can have a decimal point as for
                    676:   English (a comma might work with a correct LC_NUMERIC environment,
                    677:   otherwise the weight is truncated).
                    678:   Modification of warning when the covariates values are not 0 or
                    679:   1.
                    680:   Version 0.98g
                    681: 
                    682:   Revision 1.121  2006/03/16 17:45:01  lievre
                    683:   * imach.c (Module): Comments concerning covariates added
                    684: 
                    685:   * imach.c (Module): refinements in the computation of lli if
                    686:   status=-2 in order to have more reliable computation if stepm is
                    687:   not 1 month. Version 0.98f
                    688: 
                    689:   Revision 1.120  2006/03/16 15:10:38  lievre
                    690:   (Module): refinements in the computation of lli if
                    691:   status=-2 in order to have more reliable computation if stepm is
                    692:   not 1 month. Version 0.98f
                    693: 
                    694:   Revision 1.119  2006/03/15 17:42:26  brouard
                    695:   (Module): Bug if status = -2, the loglikelihood was
                    696:   computed as likelihood omitting the logarithm. Version O.98e
                    697: 
                    698:   Revision 1.118  2006/03/14 18:20:07  brouard
                    699:   (Module): varevsij Comments added explaining the second
                    700:   table of variances if popbased=1 .
                    701:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    702:   (Module): Function pstamp added
                    703:   (Module): Version 0.98d
                    704: 
                    705:   Revision 1.117  2006/03/14 17:16:22  brouard
                    706:   (Module): varevsij Comments added explaining the second
                    707:   table of variances if popbased=1 .
                    708:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    709:   (Module): Function pstamp added
                    710:   (Module): Version 0.98d
                    711: 
                    712:   Revision 1.116  2006/03/06 10:29:27  brouard
                    713:   (Module): Variance-covariance wrong links and
                    714:   varian-covariance of ej. is needed (Saito).
                    715: 
                    716:   Revision 1.115  2006/02/27 12:17:45  brouard
                    717:   (Module): One freematrix added in mlikeli! 0.98c
                    718: 
                    719:   Revision 1.114  2006/02/26 12:57:58  brouard
                    720:   (Module): Some improvements in processing parameter
                    721:   filename with strsep.
                    722: 
                    723:   Revision 1.113  2006/02/24 14:20:24  brouard
                    724:   (Module): Memory leaks checks with valgrind and:
                    725:   datafile was not closed, some imatrix were not freed and on matrix
                    726:   allocation too.
                    727: 
                    728:   Revision 1.112  2006/01/30 09:55:26  brouard
                    729:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    730: 
                    731:   Revision 1.111  2006/01/25 20:38:18  brouard
                    732:   (Module): Lots of cleaning and bugs added (Gompertz)
                    733:   (Module): Comments can be added in data file. Missing date values
                    734:   can be a simple dot '.'.
                    735: 
                    736:   Revision 1.110  2006/01/25 00:51:50  brouard
                    737:   (Module): Lots of cleaning and bugs added (Gompertz)
                    738: 
                    739:   Revision 1.109  2006/01/24 19:37:15  brouard
                    740:   (Module): Comments (lines starting with a #) are allowed in data.
                    741: 
                    742:   Revision 1.108  2006/01/19 18:05:42  lievre
                    743:   Gnuplot problem appeared...
                    744:   To be fixed
                    745: 
                    746:   Revision 1.107  2006/01/19 16:20:37  brouard
                    747:   Test existence of gnuplot in imach path
                    748: 
                    749:   Revision 1.106  2006/01/19 13:24:36  brouard
                    750:   Some cleaning and links added in html output
                    751: 
                    752:   Revision 1.105  2006/01/05 20:23:19  lievre
                    753:   *** empty log message ***
                    754: 
                    755:   Revision 1.104  2005/09/30 16:11:43  lievre
                    756:   (Module): sump fixed, loop imx fixed, and simplifications.
                    757:   (Module): If the status is missing at the last wave but we know
                    758:   that the person is alive, then we can code his/her status as -2
                    759:   (instead of missing=-1 in earlier versions) and his/her
                    760:   contributions to the likelihood is 1 - Prob of dying from last
                    761:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    762:   the healthy state at last known wave). Version is 0.98
                    763: 
                    764:   Revision 1.103  2005/09/30 15:54:49  lievre
                    765:   (Module): sump fixed, loop imx fixed, and simplifications.
                    766: 
                    767:   Revision 1.102  2004/09/15 17:31:30  brouard
                    768:   Add the possibility to read data file including tab characters.
                    769: 
                    770:   Revision 1.101  2004/09/15 10:38:38  brouard
                    771:   Fix on curr_time
                    772: 
                    773:   Revision 1.100  2004/07/12 18:29:06  brouard
                    774:   Add version for Mac OS X. Just define UNIX in Makefile
                    775: 
                    776:   Revision 1.99  2004/06/05 08:57:40  brouard
                    777:   *** empty log message ***
                    778: 
                    779:   Revision 1.98  2004/05/16 15:05:56  brouard
                    780:   New version 0.97 . First attempt to estimate force of mortality
                    781:   directly from the data i.e. without the need of knowing the health
                    782:   state at each age, but using a Gompertz model: log u =a + b*age .
                    783:   This is the basic analysis of mortality and should be done before any
                    784:   other analysis, in order to test if the mortality estimated from the
                    785:   cross-longitudinal survey is different from the mortality estimated
                    786:   from other sources like vital statistic data.
                    787: 
                    788:   The same imach parameter file can be used but the option for mle should be -3.
                    789: 
1.133     brouard   790:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   791:   former routines in order to include the new code within the former code.
                    792: 
                    793:   The output is very simple: only an estimate of the intercept and of
                    794:   the slope with 95% confident intervals.
                    795: 
                    796:   Current limitations:
                    797:   A) Even if you enter covariates, i.e. with the
                    798:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    799:   B) There is no computation of Life Expectancy nor Life Table.
                    800: 
                    801:   Revision 1.97  2004/02/20 13:25:42  lievre
                    802:   Version 0.96d. Population forecasting command line is (temporarily)
                    803:   suppressed.
                    804: 
                    805:   Revision 1.96  2003/07/15 15:38:55  brouard
                    806:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    807:   rewritten within the same printf. Workaround: many printfs.
                    808: 
                    809:   Revision 1.95  2003/07/08 07:54:34  brouard
                    810:   * imach.c (Repository):
                    811:   (Repository): Using imachwizard code to output a more meaningful covariance
                    812:   matrix (cov(a12,c31) instead of numbers.
                    813: 
                    814:   Revision 1.94  2003/06/27 13:00:02  brouard
                    815:   Just cleaning
                    816: 
                    817:   Revision 1.93  2003/06/25 16:33:55  brouard
                    818:   (Module): On windows (cygwin) function asctime_r doesn't
                    819:   exist so I changed back to asctime which exists.
                    820:   (Module): Version 0.96b
                    821: 
                    822:   Revision 1.92  2003/06/25 16:30:45  brouard
                    823:   (Module): On windows (cygwin) function asctime_r doesn't
                    824:   exist so I changed back to asctime which exists.
                    825: 
                    826:   Revision 1.91  2003/06/25 15:30:29  brouard
                    827:   * imach.c (Repository): Duplicated warning errors corrected.
                    828:   (Repository): Elapsed time after each iteration is now output. It
                    829:   helps to forecast when convergence will be reached. Elapsed time
                    830:   is stamped in powell.  We created a new html file for the graphs
                    831:   concerning matrix of covariance. It has extension -cov.htm.
                    832: 
                    833:   Revision 1.90  2003/06/24 12:34:15  brouard
                    834:   (Module): Some bugs corrected for windows. Also, when
                    835:   mle=-1 a template is output in file "or"mypar.txt with the design
                    836:   of the covariance matrix to be input.
                    837: 
                    838:   Revision 1.89  2003/06/24 12:30:52  brouard
                    839:   (Module): Some bugs corrected for windows. Also, when
                    840:   mle=-1 a template is output in file "or"mypar.txt with the design
                    841:   of the covariance matrix to be input.
                    842: 
                    843:   Revision 1.88  2003/06/23 17:54:56  brouard
                    844:   * 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.
                    845: 
                    846:   Revision 1.87  2003/06/18 12:26:01  brouard
                    847:   Version 0.96
                    848: 
                    849:   Revision 1.86  2003/06/17 20:04:08  brouard
                    850:   (Module): Change position of html and gnuplot routines and added
                    851:   routine fileappend.
                    852: 
                    853:   Revision 1.85  2003/06/17 13:12:43  brouard
                    854:   * imach.c (Repository): Check when date of death was earlier that
                    855:   current date of interview. It may happen when the death was just
                    856:   prior to the death. In this case, dh was negative and likelihood
                    857:   was wrong (infinity). We still send an "Error" but patch by
                    858:   assuming that the date of death was just one stepm after the
                    859:   interview.
                    860:   (Repository): Because some people have very long ID (first column)
                    861:   we changed int to long in num[] and we added a new lvector for
                    862:   memory allocation. But we also truncated to 8 characters (left
                    863:   truncation)
                    864:   (Repository): No more line truncation errors.
                    865: 
                    866:   Revision 1.84  2003/06/13 21:44:43  brouard
                    867:   * imach.c (Repository): Replace "freqsummary" at a correct
                    868:   place. It differs from routine "prevalence" which may be called
                    869:   many times. Probs is memory consuming and must be used with
                    870:   parcimony.
                    871:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    872: 
                    873:   Revision 1.83  2003/06/10 13:39:11  lievre
                    874:   *** empty log message ***
                    875: 
                    876:   Revision 1.82  2003/06/05 15:57:20  brouard
                    877:   Add log in  imach.c and  fullversion number is now printed.
                    878: 
                    879: */
                    880: /*
                    881:    Interpolated Markov Chain
                    882: 
                    883:   Short summary of the programme:
                    884:   
1.227     brouard   885:   This program computes Healthy Life Expectancies or State-specific
                    886:   (if states aren't health statuses) Expectancies from
                    887:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    888: 
                    889:   -1- a first survey ("cross") where individuals from different ages
                    890:   are interviewed on their health status or degree of disability (in
                    891:   the case of a health survey which is our main interest)
                    892: 
                    893:   -2- at least a second wave of interviews ("longitudinal") which
                    894:   measure each change (if any) in individual health status.  Health
                    895:   expectancies are computed from the time spent in each health state
                    896:   according to a model. More health states you consider, more time is
                    897:   necessary to reach the Maximum Likelihood of the parameters involved
                    898:   in the model.  The simplest model is the multinomial logistic model
                    899:   where pij is the probability to be observed in state j at the second
                    900:   wave conditional to be observed in state i at the first
                    901:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    902:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    903:   have a more complex model than "constant and age", you should modify
                    904:   the program where the markup *Covariates have to be included here
                    905:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   906:   convergence.
                    907: 
                    908:   The advantage of this computer programme, compared to a simple
                    909:   multinomial logistic model, is clear when the delay between waves is not
                    910:   identical for each individual. Also, if a individual missed an
                    911:   intermediate interview, the information is lost, but taken into
                    912:   account using an interpolation or extrapolation.  
                    913: 
                    914:   hPijx is the probability to be observed in state i at age x+h
                    915:   conditional to the observed state i at age x. The delay 'h' can be
                    916:   split into an exact number (nh*stepm) of unobserved intermediate
                    917:   states. This elementary transition (by month, quarter,
                    918:   semester or year) is modelled as a multinomial logistic.  The hPx
                    919:   matrix is simply the matrix product of nh*stepm elementary matrices
                    920:   and the contribution of each individual to the likelihood is simply
                    921:   hPijx.
                    922: 
                    923:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   924:   of the life expectancies. It also computes the period (stable) prevalence.
                    925: 
                    926: Back prevalence and projections:
1.227     brouard   927: 
                    928:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    929:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    930:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    931:    mobilavproj)
                    932: 
                    933:     Computes the back prevalence limit for any combination of
                    934:     covariate values k at any age between ageminpar and agemaxpar and
                    935:     returns it in **bprlim. In the loops,
                    936: 
                    937:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    938:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    939: 
                    940:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   941:    Computes for any combination of covariates k and any age between bage and fage 
                    942:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    943:                        oldm=oldms;savm=savms;
1.227     brouard   944: 
1.267     brouard   945:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard   946:      Computes the transition matrix starting at age 'age' over
                    947:      'nhstepm*hstepm*stepm' months (i.e. until
                    948:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   949:      nhstepm*hstepm matrices. 
                    950: 
                    951:      Returns p3mat[i][j][h] after calling
                    952:      p3mat[i][j][h]=matprod2(newm,
                    953:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    954:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    955:      oldm);
1.226     brouard   956: 
                    957: Important routines
                    958: 
                    959: - func (or funcone), computes logit (pij) distinguishing
                    960:   o fixed variables (single or product dummies or quantitative);
                    961:   o varying variables by:
                    962:    (1) wave (single, product dummies, quantitative), 
                    963:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    964:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    965:        % varying dummy (not done) or quantitative (not done);
                    966: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    967:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    968: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    969:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    970:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   971: 
1.226     brouard   972: 
                    973:   
1.133     brouard   974:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    975:            Institut national d'études démographiques, Paris.
1.126     brouard   976:   This software have been partly granted by Euro-REVES, a concerted action
                    977:   from the European Union.
                    978:   It is copyrighted identically to a GNU software product, ie programme and
                    979:   software can be distributed freely for non commercial use. Latest version
                    980:   can be accessed at http://euroreves.ined.fr/imach .
                    981: 
                    982:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    983:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    984:   
                    985:   **********************************************************************/
                    986: /*
                    987:   main
                    988:   read parameterfile
                    989:   read datafile
                    990:   concatwav
                    991:   freqsummary
                    992:   if (mle >= 1)
                    993:     mlikeli
                    994:   print results files
                    995:   if mle==1 
                    996:      computes hessian
                    997:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    998:       begin-prev-date,...
                    999:   open gnuplot file
                   1000:   open html file
1.145     brouard  1001:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1002:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1003:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1004:     freexexit2 possible for memory heap.
                   1005: 
                   1006:   h Pij x                         | pij_nom  ficrestpij
                   1007:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1008:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1009:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1010: 
                   1011:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1012:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1013:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1014:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1015:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1016: 
1.126     brouard  1017:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1018:   health expectancies
                   1019:   Variance-covariance of DFLE
                   1020:   prevalence()
                   1021:    movingaverage()
                   1022:   varevsij() 
                   1023:   if popbased==1 varevsij(,popbased)
                   1024:   total life expectancies
                   1025:   Variance of period (stable) prevalence
                   1026:  end
                   1027: */
                   1028: 
1.187     brouard  1029: /* #define DEBUG */
                   1030: /* #define DEBUGBRENT */
1.203     brouard  1031: /* #define DEBUGLINMIN */
                   1032: /* #define DEBUGHESS */
                   1033: #define DEBUGHESSIJ
1.224     brouard  1034: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1035: #define POWELL /* Instead of NLOPT */
1.224     brouard  1036: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1037: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1038: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1039: 
                   1040: #include <math.h>
                   1041: #include <stdio.h>
                   1042: #include <stdlib.h>
                   1043: #include <string.h>
1.226     brouard  1044: #include <ctype.h>
1.159     brouard  1045: 
                   1046: #ifdef _WIN32
                   1047: #include <io.h>
1.172     brouard  1048: #include <windows.h>
                   1049: #include <tchar.h>
1.159     brouard  1050: #else
1.126     brouard  1051: #include <unistd.h>
1.159     brouard  1052: #endif
1.126     brouard  1053: 
                   1054: #include <limits.h>
                   1055: #include <sys/types.h>
1.171     brouard  1056: 
                   1057: #if defined(__GNUC__)
                   1058: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1059: #endif
                   1060: 
1.126     brouard  1061: #include <sys/stat.h>
                   1062: #include <errno.h>
1.159     brouard  1063: /* extern int errno; */
1.126     brouard  1064: 
1.157     brouard  1065: /* #ifdef LINUX */
                   1066: /* #include <time.h> */
                   1067: /* #include "timeval.h" */
                   1068: /* #else */
                   1069: /* #include <sys/time.h> */
                   1070: /* #endif */
                   1071: 
1.126     brouard  1072: #include <time.h>
                   1073: 
1.136     brouard  1074: #ifdef GSL
                   1075: #include <gsl/gsl_errno.h>
                   1076: #include <gsl/gsl_multimin.h>
                   1077: #endif
                   1078: 
1.167     brouard  1079: 
1.162     brouard  1080: #ifdef NLOPT
                   1081: #include <nlopt.h>
                   1082: typedef struct {
                   1083:   double (* function)(double [] );
                   1084: } myfunc_data ;
                   1085: #endif
                   1086: 
1.126     brouard  1087: /* #include <libintl.h> */
                   1088: /* #define _(String) gettext (String) */
                   1089: 
1.251     brouard  1090: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1091: 
                   1092: #define GNUPLOTPROGRAM "gnuplot"
                   1093: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1094: #define FILENAMELENGTH 132
                   1095: 
                   1096: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1097: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1098: 
1.144     brouard  1099: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1100: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1101: 
                   1102: #define NINTERVMAX 8
1.144     brouard  1103: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1104: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1105: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1106: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1107: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1108: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1109: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1110: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1111: /* #define AGESUP 130 */
1.288     brouard  1112: /* #define AGESUP 150 */
                   1113: #define AGESUP 200
1.268     brouard  1114: #define AGEINF 0
1.218     brouard  1115: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1116: #define AGEBASE 40
1.194     brouard  1117: #define AGEOVERFLOW 1.e20
1.164     brouard  1118: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1119: #ifdef _WIN32
                   1120: #define DIRSEPARATOR '\\'
                   1121: #define CHARSEPARATOR "\\"
                   1122: #define ODIRSEPARATOR '/'
                   1123: #else
1.126     brouard  1124: #define DIRSEPARATOR '/'
                   1125: #define CHARSEPARATOR "/"
                   1126: #define ODIRSEPARATOR '\\'
                   1127: #endif
                   1128: 
1.303   ! brouard  1129: /* $Id: imach.c,v 1.302 2020/02/22 21:00:05 brouard Exp $ */
1.126     brouard  1130: /* $State: Exp $ */
1.196     brouard  1131: #include "version.h"
                   1132: char version[]=__IMACH_VERSION__;
1.300     brouard  1133: char copyright[]="May 2019,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020";
1.303   ! brouard  1134: char fullversion[]="$Revision: 1.302 $ $Date: 2020/02/22 21:00:05 $"; 
1.126     brouard  1135: char strstart[80];
                   1136: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1137: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1138: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1139: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1140: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1141: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1142: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1143: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1144: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1145: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1146: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1147: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1148: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1149: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1150: int nsd=0; /**< Total number of single dummy variables (output) */
                   1151: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1152: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1153: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1154: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1155: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1156: int cptcov=0; /* Working variable */
1.290     brouard  1157: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1158: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1159: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1160: int nlstate=2; /* Number of live states */
                   1161: int ndeath=1; /* Number of dead states */
1.130     brouard  1162: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1163: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1164: int popbased=0;
                   1165: 
                   1166: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1167: int maxwav=0; /* Maxim number of waves */
                   1168: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1169: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1170: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1171:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1172: int mle=1, weightopt=0;
1.126     brouard  1173: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1174: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1175: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1176:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1177: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1178: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1179: 
1.130     brouard  1180: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1181: double **matprod2(); /* test */
1.126     brouard  1182: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1183: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1184: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1185: 
1.136     brouard  1186: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1187: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1188: FILE *ficlog, *ficrespow;
1.130     brouard  1189: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1190: double fretone; /* Only one call to likelihood */
1.130     brouard  1191: long ipmx=0; /* Number of contributions */
1.126     brouard  1192: double sw; /* Sum of weights */
                   1193: char filerespow[FILENAMELENGTH];
                   1194: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1195: FILE *ficresilk;
                   1196: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1197: FILE *ficresprobmorprev;
                   1198: FILE *fichtm, *fichtmcov; /* Html File */
                   1199: FILE *ficreseij;
                   1200: char filerese[FILENAMELENGTH];
                   1201: FILE *ficresstdeij;
                   1202: char fileresstde[FILENAMELENGTH];
                   1203: FILE *ficrescveij;
                   1204: char filerescve[FILENAMELENGTH];
                   1205: FILE  *ficresvij;
                   1206: char fileresv[FILENAMELENGTH];
1.269     brouard  1207: 
1.126     brouard  1208: char title[MAXLINE];
1.234     brouard  1209: char model[MAXLINE]; /**< The model line */
1.217     brouard  1210: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1211: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1212: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1213: char command[FILENAMELENGTH];
                   1214: int  outcmd=0;
                   1215: 
1.217     brouard  1216: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1217: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1218: char filelog[FILENAMELENGTH]; /* Log file */
                   1219: char filerest[FILENAMELENGTH];
                   1220: char fileregp[FILENAMELENGTH];
                   1221: char popfile[FILENAMELENGTH];
                   1222: 
                   1223: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1224: 
1.157     brouard  1225: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1226: /* struct timezone tzp; */
                   1227: /* extern int gettimeofday(); */
                   1228: struct tm tml, *gmtime(), *localtime();
                   1229: 
                   1230: extern time_t time();
                   1231: 
                   1232: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1233: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1234: struct tm tm;
                   1235: 
1.126     brouard  1236: char strcurr[80], strfor[80];
                   1237: 
                   1238: char *endptr;
                   1239: long lval;
                   1240: double dval;
                   1241: 
                   1242: #define NR_END 1
                   1243: #define FREE_ARG char*
                   1244: #define FTOL 1.0e-10
                   1245: 
                   1246: #define NRANSI 
1.240     brouard  1247: #define ITMAX 200
                   1248: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1249: 
                   1250: #define TOL 2.0e-4 
                   1251: 
                   1252: #define CGOLD 0.3819660 
                   1253: #define ZEPS 1.0e-10 
                   1254: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1255: 
                   1256: #define GOLD 1.618034 
                   1257: #define GLIMIT 100.0 
                   1258: #define TINY 1.0e-20 
                   1259: 
                   1260: static double maxarg1,maxarg2;
                   1261: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1262: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1263:   
                   1264: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1265: #define rint(a) floor(a+0.5)
1.166     brouard  1266: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1267: #define mytinydouble 1.0e-16
1.166     brouard  1268: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1269: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1270: /* static double dsqrarg; */
                   1271: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1272: static double sqrarg;
                   1273: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1274: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1275: int agegomp= AGEGOMP;
                   1276: 
                   1277: int imx; 
                   1278: int stepm=1;
                   1279: /* Stepm, step in month: minimum step interpolation*/
                   1280: 
                   1281: int estepm;
                   1282: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1283: 
                   1284: int m,nb;
                   1285: long *num;
1.197     brouard  1286: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1287: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1288:                   covariate for which somebody answered excluding 
                   1289:                   undefined. Usually 2: 0 and 1. */
                   1290: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1291:                             covariate for which somebody answered including 
                   1292:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1293: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1294: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1295: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1296: double *ageexmed,*agecens;
                   1297: double dateintmean=0;
1.296     brouard  1298:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1299:   double anprojf, mprojf, jprojf;
1.126     brouard  1300: 
1.296     brouard  1301:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1302:   double anbackf, mbackf, jbackf;
                   1303:   double jintmean,mintmean,aintmean;  
1.126     brouard  1304: double *weight;
                   1305: int **s; /* Status */
1.141     brouard  1306: double *agedc;
1.145     brouard  1307: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1308:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1309:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1310: double **coqvar; /* Fixed quantitative covariate nqv */
                   1311: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1312: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1313: double  idx; 
                   1314: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1315: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1316: /*k          1  2   3   4     5    6    7     8    9 */
                   1317: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1318: /* Tndvar[k]    1   2   3               4          5 */
                   1319: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1320: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1321: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1322: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1323: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1324: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1325: /* Tprod[i]=k           4               7            */
                   1326: /* Tage[i]=k                  5               8      */
                   1327: /* */
                   1328: /* Type                    */
                   1329: /* V         1  2  3  4  5 */
                   1330: /*           F  F  V  V  V */
                   1331: /*           D  Q  D  D  Q */
                   1332: /*                         */
                   1333: int *TvarsD;
                   1334: int *TvarsDind;
                   1335: int *TvarsQ;
                   1336: int *TvarsQind;
                   1337: 
1.235     brouard  1338: #define MAXRESULTLINES 10
                   1339: int nresult=0;
1.258     brouard  1340: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1341: int TKresult[MAXRESULTLINES];
1.237     brouard  1342: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1343: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1344: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1345: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1346: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1347: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1348: 
1.234     brouard  1349: /* 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  1350: 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 */
                   1351: 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 */
                   1352: 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 */
                   1353: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1354: 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 */
                   1355: 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  1356: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1357: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1358: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1359: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1360: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1361: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1362: 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 */
                   1363: 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 */
                   1364: 
1.230     brouard  1365: int *Tvarsel; /**< Selected covariates for output */
                   1366: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1367: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1368: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1369: 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  1370: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1371: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1372: int *Tage;
1.227     brouard  1373: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1374: 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  1375: 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*/ 
                   1376: 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  1377: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1378: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1379: int **Tvard;
                   1380: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1381: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1382: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1383:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1384:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1385: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1386: double *lsurv, *lpop, *tpop;
                   1387: 
1.231     brouard  1388: #define FD 1; /* Fixed dummy covariate */
                   1389: #define FQ 2; /* Fixed quantitative covariate */
                   1390: #define FP 3; /* Fixed product covariate */
                   1391: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1392: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1393: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1394: #define VD 10; /* Varying dummy covariate */
                   1395: #define VQ 11; /* Varying quantitative covariate */
                   1396: #define VP 12; /* Varying product covariate */
                   1397: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1398: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1399: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1400: #define APFD 16; /* Age product * fixed dummy covariate */
                   1401: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1402: #define APVD 18; /* Age product * varying dummy covariate */
                   1403: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1404: 
                   1405: #define FTYPE 1; /* Fixed covariate */
                   1406: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1407: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1408: 
                   1409: struct kmodel{
                   1410:        int maintype; /* main type */
                   1411:        int subtype; /* subtype */
                   1412: };
                   1413: struct kmodel modell[NCOVMAX];
                   1414: 
1.143     brouard  1415: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1416: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1417: 
                   1418: /**************** split *************************/
                   1419: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1420: {
                   1421:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1422:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1423:   */ 
                   1424:   char *ss;                            /* pointer */
1.186     brouard  1425:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1426: 
                   1427:   l1 = strlen(path );                  /* length of path */
                   1428:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1429:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1430:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1431:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1432:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1433:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1434:     /* get current working directory */
                   1435:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1436: #ifdef WIN32
                   1437:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1438: #else
                   1439:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1440: #endif
1.126     brouard  1441:       return( GLOCK_ERROR_GETCWD );
                   1442:     }
                   1443:     /* got dirc from getcwd*/
                   1444:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1445:   } else {                             /* strip directory from path */
1.126     brouard  1446:     ss++;                              /* after this, the filename */
                   1447:     l2 = strlen( ss );                 /* length of filename */
                   1448:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1449:     strcpy( name, ss );                /* save file name */
                   1450:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1451:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1452:     printf(" DIRC2 = %s \n",dirc);
                   1453:   }
                   1454:   /* We add a separator at the end of dirc if not exists */
                   1455:   l1 = strlen( dirc );                 /* length of directory */
                   1456:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1457:     dirc[l1] =  DIRSEPARATOR;
                   1458:     dirc[l1+1] = 0; 
                   1459:     printf(" DIRC3 = %s \n",dirc);
                   1460:   }
                   1461:   ss = strrchr( name, '.' );           /* find last / */
                   1462:   if (ss >0){
                   1463:     ss++;
                   1464:     strcpy(ext,ss);                    /* save extension */
                   1465:     l1= strlen( name);
                   1466:     l2= strlen(ss)+1;
                   1467:     strncpy( finame, name, l1-l2);
                   1468:     finame[l1-l2]= 0;
                   1469:   }
                   1470: 
                   1471:   return( 0 );                         /* we're done */
                   1472: }
                   1473: 
                   1474: 
                   1475: /******************************************/
                   1476: 
                   1477: void replace_back_to_slash(char *s, char*t)
                   1478: {
                   1479:   int i;
                   1480:   int lg=0;
                   1481:   i=0;
                   1482:   lg=strlen(t);
                   1483:   for(i=0; i<= lg; i++) {
                   1484:     (s[i] = t[i]);
                   1485:     if (t[i]== '\\') s[i]='/';
                   1486:   }
                   1487: }
                   1488: 
1.132     brouard  1489: char *trimbb(char *out, char *in)
1.137     brouard  1490: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1491:   char *s;
                   1492:   s=out;
                   1493:   while (*in != '\0'){
1.137     brouard  1494:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1495:       in++;
                   1496:     }
                   1497:     *out++ = *in++;
                   1498:   }
                   1499:   *out='\0';
                   1500:   return s;
                   1501: }
                   1502: 
1.187     brouard  1503: /* char *substrchaine(char *out, char *in, char *chain) */
                   1504: /* { */
                   1505: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1506: /*   char *s, *t; */
                   1507: /*   t=in;s=out; */
                   1508: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1509: /*     *out++ = *in++; */
                   1510: /*   } */
                   1511: 
                   1512: /*   /\* *in matches *chain *\/ */
                   1513: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1514: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1515: /*   } */
                   1516: /*   in--; chain--; */
                   1517: /*   while ( (*in != '\0')){ */
                   1518: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1519: /*     *out++ = *in++; */
                   1520: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1521: /*   } */
                   1522: /*   *out='\0'; */
                   1523: /*   out=s; */
                   1524: /*   return out; */
                   1525: /* } */
                   1526: char *substrchaine(char *out, char *in, char *chain)
                   1527: {
                   1528:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1529:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1530: 
                   1531:   char *strloc;
                   1532: 
                   1533:   strcpy (out, in); 
                   1534:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1535:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1536:   if(strloc != NULL){ 
                   1537:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1538:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1539:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1540:   }
                   1541:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1542:   return out;
                   1543: }
                   1544: 
                   1545: 
1.145     brouard  1546: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1547: {
1.187     brouard  1548:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1549:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1550:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1551:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1552:   */
1.160     brouard  1553:   char *s, *t;
1.145     brouard  1554:   t=in;s=in;
                   1555:   while ((*in != occ) && (*in != '\0')){
                   1556:     *alocc++ = *in++;
                   1557:   }
                   1558:   if( *in == occ){
                   1559:     *(alocc)='\0';
                   1560:     s=++in;
                   1561:   }
                   1562:  
                   1563:   if (s == t) {/* occ not found */
                   1564:     *(alocc-(in-s))='\0';
                   1565:     in=s;
                   1566:   }
                   1567:   while ( *in != '\0'){
                   1568:     *blocc++ = *in++;
                   1569:   }
                   1570: 
                   1571:   *blocc='\0';
                   1572:   return t;
                   1573: }
1.137     brouard  1574: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1575: {
1.187     brouard  1576:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1577:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1578:      gives blocc="abcdef2ghi" and alocc="j".
                   1579:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1580:   */
                   1581:   char *s, *t;
                   1582:   t=in;s=in;
                   1583:   while (*in != '\0'){
                   1584:     while( *in == occ){
                   1585:       *blocc++ = *in++;
                   1586:       s=in;
                   1587:     }
                   1588:     *blocc++ = *in++;
                   1589:   }
                   1590:   if (s == t) /* occ not found */
                   1591:     *(blocc-(in-s))='\0';
                   1592:   else
                   1593:     *(blocc-(in-s)-1)='\0';
                   1594:   in=s;
                   1595:   while ( *in != '\0'){
                   1596:     *alocc++ = *in++;
                   1597:   }
                   1598: 
                   1599:   *alocc='\0';
                   1600:   return s;
                   1601: }
                   1602: 
1.126     brouard  1603: int nbocc(char *s, char occ)
                   1604: {
                   1605:   int i,j=0;
                   1606:   int lg=20;
                   1607:   i=0;
                   1608:   lg=strlen(s);
                   1609:   for(i=0; i<= lg; i++) {
1.234     brouard  1610:     if  (s[i] == occ ) j++;
1.126     brouard  1611:   }
                   1612:   return j;
                   1613: }
                   1614: 
1.137     brouard  1615: /* void cutv(char *u,char *v, char*t, char occ) */
                   1616: /* { */
                   1617: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1618: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1619: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1620: /*   int i,lg,j,p=0; */
                   1621: /*   i=0; */
                   1622: /*   lg=strlen(t); */
                   1623: /*   for(j=0; j<=lg-1; j++) { */
                   1624: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1625: /*   } */
1.126     brouard  1626: 
1.137     brouard  1627: /*   for(j=0; j<p; j++) { */
                   1628: /*     (u[j] = t[j]); */
                   1629: /*   } */
                   1630: /*      u[p]='\0'; */
1.126     brouard  1631: 
1.137     brouard  1632: /*    for(j=0; j<= lg; j++) { */
                   1633: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1634: /*   } */
                   1635: /* } */
1.126     brouard  1636: 
1.160     brouard  1637: #ifdef _WIN32
                   1638: char * strsep(char **pp, const char *delim)
                   1639: {
                   1640:   char *p, *q;
                   1641:          
                   1642:   if ((p = *pp) == NULL)
                   1643:     return 0;
                   1644:   if ((q = strpbrk (p, delim)) != NULL)
                   1645:   {
                   1646:     *pp = q + 1;
                   1647:     *q = '\0';
                   1648:   }
                   1649:   else
                   1650:     *pp = 0;
                   1651:   return p;
                   1652: }
                   1653: #endif
                   1654: 
1.126     brouard  1655: /********************** nrerror ********************/
                   1656: 
                   1657: void nrerror(char error_text[])
                   1658: {
                   1659:   fprintf(stderr,"ERREUR ...\n");
                   1660:   fprintf(stderr,"%s\n",error_text);
                   1661:   exit(EXIT_FAILURE);
                   1662: }
                   1663: /*********************** vector *******************/
                   1664: double *vector(int nl, int nh)
                   1665: {
                   1666:   double *v;
                   1667:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1668:   if (!v) nrerror("allocation failure in vector");
                   1669:   return v-nl+NR_END;
                   1670: }
                   1671: 
                   1672: /************************ free vector ******************/
                   1673: void free_vector(double*v, int nl, int nh)
                   1674: {
                   1675:   free((FREE_ARG)(v+nl-NR_END));
                   1676: }
                   1677: 
                   1678: /************************ivector *******************************/
                   1679: int *ivector(long nl,long nh)
                   1680: {
                   1681:   int *v;
                   1682:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1683:   if (!v) nrerror("allocation failure in ivector");
                   1684:   return v-nl+NR_END;
                   1685: }
                   1686: 
                   1687: /******************free ivector **************************/
                   1688: void free_ivector(int *v, long nl, long nh)
                   1689: {
                   1690:   free((FREE_ARG)(v+nl-NR_END));
                   1691: }
                   1692: 
                   1693: /************************lvector *******************************/
                   1694: long *lvector(long nl,long nh)
                   1695: {
                   1696:   long *v;
                   1697:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1698:   if (!v) nrerror("allocation failure in ivector");
                   1699:   return v-nl+NR_END;
                   1700: }
                   1701: 
                   1702: /******************free lvector **************************/
                   1703: void free_lvector(long *v, long nl, long nh)
                   1704: {
                   1705:   free((FREE_ARG)(v+nl-NR_END));
                   1706: }
                   1707: 
                   1708: /******************* imatrix *******************************/
                   1709: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1710:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1711: { 
                   1712:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1713:   int **m; 
                   1714:   
                   1715:   /* allocate pointers to rows */ 
                   1716:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1717:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1718:   m += NR_END; 
                   1719:   m -= nrl; 
                   1720:   
                   1721:   
                   1722:   /* allocate rows and set pointers to them */ 
                   1723:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1724:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1725:   m[nrl] += NR_END; 
                   1726:   m[nrl] -= ncl; 
                   1727:   
                   1728:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1729:   
                   1730:   /* return pointer to array of pointers to rows */ 
                   1731:   return m; 
                   1732: } 
                   1733: 
                   1734: /****************** free_imatrix *************************/
                   1735: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1736:       int **m;
                   1737:       long nch,ncl,nrh,nrl; 
                   1738:      /* free an int matrix allocated by imatrix() */ 
                   1739: { 
                   1740:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1741:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1742: } 
                   1743: 
                   1744: /******************* matrix *******************************/
                   1745: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1746: {
                   1747:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1748:   double **m;
                   1749: 
                   1750:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1751:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1752:   m += NR_END;
                   1753:   m -= nrl;
                   1754: 
                   1755:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1756:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1757:   m[nrl] += NR_END;
                   1758:   m[nrl] -= ncl;
                   1759: 
                   1760:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1761:   return m;
1.145     brouard  1762:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1763: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1764: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1765:    */
                   1766: }
                   1767: 
                   1768: /*************************free matrix ************************/
                   1769: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1770: {
                   1771:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1772:   free((FREE_ARG)(m+nrl-NR_END));
                   1773: }
                   1774: 
                   1775: /******************* ma3x *******************************/
                   1776: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1777: {
                   1778:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1779:   double ***m;
                   1780: 
                   1781:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1782:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1783:   m += NR_END;
                   1784:   m -= nrl;
                   1785: 
                   1786:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1787:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1788:   m[nrl] += NR_END;
                   1789:   m[nrl] -= ncl;
                   1790: 
                   1791:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1792: 
                   1793:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1794:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1795:   m[nrl][ncl] += NR_END;
                   1796:   m[nrl][ncl] -= nll;
                   1797:   for (j=ncl+1; j<=nch; j++) 
                   1798:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1799:   
                   1800:   for (i=nrl+1; i<=nrh; i++) {
                   1801:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1802:     for (j=ncl+1; j<=nch; j++) 
                   1803:       m[i][j]=m[i][j-1]+nlay;
                   1804:   }
                   1805:   return m; 
                   1806:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1807:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1808:   */
                   1809: }
                   1810: 
                   1811: /*************************free ma3x ************************/
                   1812: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1813: {
                   1814:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1815:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1816:   free((FREE_ARG)(m+nrl-NR_END));
                   1817: }
                   1818: 
                   1819: /*************** function subdirf ***********/
                   1820: char *subdirf(char fileres[])
                   1821: {
                   1822:   /* Caution optionfilefiname is hidden */
                   1823:   strcpy(tmpout,optionfilefiname);
                   1824:   strcat(tmpout,"/"); /* Add to the right */
                   1825:   strcat(tmpout,fileres);
                   1826:   return tmpout;
                   1827: }
                   1828: 
                   1829: /*************** function subdirf2 ***********/
                   1830: char *subdirf2(char fileres[], char *preop)
                   1831: {
                   1832:   
                   1833:   /* Caution optionfilefiname is hidden */
                   1834:   strcpy(tmpout,optionfilefiname);
                   1835:   strcat(tmpout,"/");
                   1836:   strcat(tmpout,preop);
                   1837:   strcat(tmpout,fileres);
                   1838:   return tmpout;
                   1839: }
                   1840: 
                   1841: /*************** function subdirf3 ***********/
                   1842: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1843: {
                   1844:   
                   1845:   /* Caution optionfilefiname is hidden */
                   1846:   strcpy(tmpout,optionfilefiname);
                   1847:   strcat(tmpout,"/");
                   1848:   strcat(tmpout,preop);
                   1849:   strcat(tmpout,preop2);
                   1850:   strcat(tmpout,fileres);
                   1851:   return tmpout;
                   1852: }
1.213     brouard  1853:  
                   1854: /*************** function subdirfext ***********/
                   1855: char *subdirfext(char fileres[], char *preop, char *postop)
                   1856: {
                   1857:   
                   1858:   strcpy(tmpout,preop);
                   1859:   strcat(tmpout,fileres);
                   1860:   strcat(tmpout,postop);
                   1861:   return tmpout;
                   1862: }
1.126     brouard  1863: 
1.213     brouard  1864: /*************** function subdirfext3 ***********/
                   1865: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1866: {
                   1867:   
                   1868:   /* Caution optionfilefiname is hidden */
                   1869:   strcpy(tmpout,optionfilefiname);
                   1870:   strcat(tmpout,"/");
                   1871:   strcat(tmpout,preop);
                   1872:   strcat(tmpout,fileres);
                   1873:   strcat(tmpout,postop);
                   1874:   return tmpout;
                   1875: }
                   1876:  
1.162     brouard  1877: char *asc_diff_time(long time_sec, char ascdiff[])
                   1878: {
                   1879:   long sec_left, days, hours, minutes;
                   1880:   days = (time_sec) / (60*60*24);
                   1881:   sec_left = (time_sec) % (60*60*24);
                   1882:   hours = (sec_left) / (60*60) ;
                   1883:   sec_left = (sec_left) %(60*60);
                   1884:   minutes = (sec_left) /60;
                   1885:   sec_left = (sec_left) % (60);
                   1886:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1887:   return ascdiff;
                   1888: }
                   1889: 
1.126     brouard  1890: /***************** f1dim *************************/
                   1891: extern int ncom; 
                   1892: extern double *pcom,*xicom;
                   1893: extern double (*nrfunc)(double []); 
                   1894:  
                   1895: double f1dim(double x) 
                   1896: { 
                   1897:   int j; 
                   1898:   double f;
                   1899:   double *xt; 
                   1900:  
                   1901:   xt=vector(1,ncom); 
                   1902:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1903:   f=(*nrfunc)(xt); 
                   1904:   free_vector(xt,1,ncom); 
                   1905:   return f; 
                   1906: } 
                   1907: 
                   1908: /*****************brent *************************/
                   1909: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1910: {
                   1911:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1912:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1913:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1914:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1915:    * returned function value. 
                   1916:   */
1.126     brouard  1917:   int iter; 
                   1918:   double a,b,d,etemp;
1.159     brouard  1919:   double fu=0,fv,fw,fx;
1.164     brouard  1920:   double ftemp=0.;
1.126     brouard  1921:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1922:   double e=0.0; 
                   1923:  
                   1924:   a=(ax < cx ? ax : cx); 
                   1925:   b=(ax > cx ? ax : cx); 
                   1926:   x=w=v=bx; 
                   1927:   fw=fv=fx=(*f)(x); 
                   1928:   for (iter=1;iter<=ITMAX;iter++) { 
                   1929:     xm=0.5*(a+b); 
                   1930:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1931:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1932:     printf(".");fflush(stdout);
                   1933:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1934: #ifdef DEBUGBRENT
1.126     brouard  1935:     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);
                   1936:     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);
                   1937:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1938: #endif
                   1939:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1940:       *xmin=x; 
                   1941:       return fx; 
                   1942:     } 
                   1943:     ftemp=fu;
                   1944:     if (fabs(e) > tol1) { 
                   1945:       r=(x-w)*(fx-fv); 
                   1946:       q=(x-v)*(fx-fw); 
                   1947:       p=(x-v)*q-(x-w)*r; 
                   1948:       q=2.0*(q-r); 
                   1949:       if (q > 0.0) p = -p; 
                   1950:       q=fabs(q); 
                   1951:       etemp=e; 
                   1952:       e=d; 
                   1953:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1954:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1955:       else { 
1.224     brouard  1956:                                d=p/q; 
                   1957:                                u=x+d; 
                   1958:                                if (u-a < tol2 || b-u < tol2) 
                   1959:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1960:       } 
                   1961:     } else { 
                   1962:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1963:     } 
                   1964:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1965:     fu=(*f)(u); 
                   1966:     if (fu <= fx) { 
                   1967:       if (u >= x) a=x; else b=x; 
                   1968:       SHFT(v,w,x,u) 
1.183     brouard  1969:       SHFT(fv,fw,fx,fu) 
                   1970:     } else { 
                   1971:       if (u < x) a=u; else b=u; 
                   1972:       if (fu <= fw || w == x) { 
1.224     brouard  1973:                                v=w; 
                   1974:                                w=u; 
                   1975:                                fv=fw; 
                   1976:                                fw=fu; 
1.183     brouard  1977:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1978:                                v=u; 
                   1979:                                fv=fu; 
1.183     brouard  1980:       } 
                   1981:     } 
1.126     brouard  1982:   } 
                   1983:   nrerror("Too many iterations in brent"); 
                   1984:   *xmin=x; 
                   1985:   return fx; 
                   1986: } 
                   1987: 
                   1988: /****************** mnbrak ***********************/
                   1989: 
                   1990: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1991:            double (*func)(double)) 
1.183     brouard  1992: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1993: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1994: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1995: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1996:    */
1.126     brouard  1997:   double ulim,u,r,q, dum;
                   1998:   double fu; 
1.187     brouard  1999: 
                   2000:   double scale=10.;
                   2001:   int iterscale=0;
                   2002: 
                   2003:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2004:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2005: 
                   2006: 
                   2007:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2008:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2009:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2010:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2011:   /* } */
                   2012: 
1.126     brouard  2013:   if (*fb > *fa) { 
                   2014:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2015:     SHFT(dum,*fb,*fa,dum) 
                   2016:   } 
1.126     brouard  2017:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2018:   *fc=(*func)(*cx); 
1.183     brouard  2019: #ifdef DEBUG
1.224     brouard  2020:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2021:   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  2022: #endif
1.224     brouard  2023:   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  2024:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2025:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2026:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2027:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2028:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2029:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2030:       fu=(*func)(u); 
1.163     brouard  2031: #ifdef DEBUG
                   2032:       /* f(x)=A(x-u)**2+f(u) */
                   2033:       double A, fparabu; 
                   2034:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2035:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2036:       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);
                   2037:       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  2038:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2039:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2040:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2041:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2042: #endif 
1.184     brouard  2043: #ifdef MNBRAKORIGINAL
1.183     brouard  2044: #else
1.191     brouard  2045: /*       if (fu > *fc) { */
                   2046: /* #ifdef DEBUG */
                   2047: /*       printf("mnbrak4  fu > fc \n"); */
                   2048: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2049: /* #endif */
                   2050: /*     /\* 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 *\\/  *\/ */
                   2051: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2052: /*     dum=u; /\* Shifting c and u *\/ */
                   2053: /*     u = *cx; */
                   2054: /*     *cx = dum; */
                   2055: /*     dum = fu; */
                   2056: /*     fu = *fc; */
                   2057: /*     *fc =dum; */
                   2058: /*       } else { /\* end *\/ */
                   2059: /* #ifdef DEBUG */
                   2060: /*       printf("mnbrak3  fu < fc \n"); */
                   2061: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2062: /* #endif */
                   2063: /*     dum=u; /\* Shifting c and u *\/ */
                   2064: /*     u = *cx; */
                   2065: /*     *cx = dum; */
                   2066: /*     dum = fu; */
                   2067: /*     fu = *fc; */
                   2068: /*     *fc =dum; */
                   2069: /*       } */
1.224     brouard  2070: #ifdef DEBUGMNBRAK
                   2071:                 double A, fparabu; 
                   2072:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2073:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2074:      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);
                   2075:      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  2076: #endif
1.191     brouard  2077:       dum=u; /* Shifting c and u */
                   2078:       u = *cx;
                   2079:       *cx = dum;
                   2080:       dum = fu;
                   2081:       fu = *fc;
                   2082:       *fc =dum;
1.183     brouard  2083: #endif
1.162     brouard  2084:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2085: #ifdef DEBUG
1.224     brouard  2086:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2087:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2088: #endif
1.126     brouard  2089:       fu=(*func)(u); 
                   2090:       if (fu < *fc) { 
1.183     brouard  2091: #ifdef DEBUG
1.224     brouard  2092:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2093:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2094: #endif
                   2095:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2096:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2097: #ifdef DEBUG
                   2098:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2099: #endif
                   2100:       } 
1.162     brouard  2101:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2102: #ifdef DEBUG
1.224     brouard  2103:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2104:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2105: #endif
1.126     brouard  2106:       u=ulim; 
                   2107:       fu=(*func)(u); 
1.183     brouard  2108:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2109: #ifdef DEBUG
1.224     brouard  2110:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2111:       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  2112: #endif
1.126     brouard  2113:       u=(*cx)+GOLD*(*cx-*bx); 
                   2114:       fu=(*func)(u); 
1.224     brouard  2115: #ifdef DEBUG
                   2116:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2117:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2118: #endif
1.183     brouard  2119:     } /* end tests */
1.126     brouard  2120:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2121:     SHFT(*fa,*fb,*fc,fu) 
                   2122: #ifdef DEBUG
1.224     brouard  2123:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2124:       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  2125: #endif
                   2126:   } /* 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  2127: } 
                   2128: 
                   2129: /*************** linmin ************************/
1.162     brouard  2130: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2131: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2132: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2133: the value of func at the returned location p . This is actually all accomplished by calling the
                   2134: routines mnbrak and brent .*/
1.126     brouard  2135: int ncom; 
                   2136: double *pcom,*xicom;
                   2137: double (*nrfunc)(double []); 
                   2138:  
1.224     brouard  2139: #ifdef LINMINORIGINAL
1.126     brouard  2140: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2141: #else
                   2142: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2143: #endif
1.126     brouard  2144: { 
                   2145:   double brent(double ax, double bx, double cx, 
                   2146:               double (*f)(double), double tol, double *xmin); 
                   2147:   double f1dim(double x); 
                   2148:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2149:              double *fc, double (*func)(double)); 
                   2150:   int j; 
                   2151:   double xx,xmin,bx,ax; 
                   2152:   double fx,fb,fa;
1.187     brouard  2153: 
1.203     brouard  2154: #ifdef LINMINORIGINAL
                   2155: #else
                   2156:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2157: #endif
                   2158:   
1.126     brouard  2159:   ncom=n; 
                   2160:   pcom=vector(1,n); 
                   2161:   xicom=vector(1,n); 
                   2162:   nrfunc=func; 
                   2163:   for (j=1;j<=n;j++) { 
                   2164:     pcom[j]=p[j]; 
1.202     brouard  2165:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2166:   } 
1.187     brouard  2167: 
1.203     brouard  2168: #ifdef LINMINORIGINAL
                   2169:   xx=1.;
                   2170: #else
                   2171:   axs=0.0;
                   2172:   xxs=1.;
                   2173:   do{
                   2174:     xx= xxs;
                   2175: #endif
1.187     brouard  2176:     ax=0.;
                   2177:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2178:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2179:     /* 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))   */
                   2180:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2181:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2182:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2183:     /* 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  2184: #ifdef LINMINORIGINAL
                   2185: #else
                   2186:     if (fx != fx){
1.224     brouard  2187:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2188:                        printf("|");
                   2189:                        fprintf(ficlog,"|");
1.203     brouard  2190: #ifdef DEBUGLINMIN
1.224     brouard  2191:                        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  2192: #endif
                   2193:     }
1.224     brouard  2194:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2195: #endif
                   2196:   
1.191     brouard  2197: #ifdef DEBUGLINMIN
                   2198:   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  2199:   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  2200: #endif
1.224     brouard  2201: #ifdef LINMINORIGINAL
                   2202: #else
                   2203:        if(fb == fx){ /* Flat function in the direction */
                   2204:                xmin=xx;
                   2205:     *flat=1;
                   2206:        }else{
                   2207:     *flat=0;
                   2208: #endif
                   2209:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2210:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2211:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2212:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2213:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2214:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2215: #ifdef DEBUG
1.224     brouard  2216:   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);
                   2217:   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);
                   2218: #endif
                   2219: #ifdef LINMINORIGINAL
                   2220: #else
                   2221:                        }
1.126     brouard  2222: #endif
1.191     brouard  2223: #ifdef DEBUGLINMIN
                   2224:   printf("linmin end ");
1.202     brouard  2225:   fprintf(ficlog,"linmin end ");
1.191     brouard  2226: #endif
1.126     brouard  2227:   for (j=1;j<=n;j++) { 
1.203     brouard  2228: #ifdef LINMINORIGINAL
                   2229:     xi[j] *= xmin; 
                   2230: #else
                   2231: #ifdef DEBUGLINMIN
                   2232:     if(xxs <1.0)
                   2233:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2234: #endif
                   2235:     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) */
                   2236: #ifdef DEBUGLINMIN
                   2237:     if(xxs <1.0)
                   2238:       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 );
                   2239: #endif
                   2240: #endif
1.187     brouard  2241:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2242:   } 
1.191     brouard  2243: #ifdef DEBUGLINMIN
1.203     brouard  2244:   printf("\n");
1.191     brouard  2245:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2246:   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  2247:   for (j=1;j<=n;j++) { 
1.202     brouard  2248:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2249:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2250:     if(j % ncovmodel == 0){
1.191     brouard  2251:       printf("\n");
1.202     brouard  2252:       fprintf(ficlog,"\n");
                   2253:     }
1.191     brouard  2254:   }
1.203     brouard  2255: #else
1.191     brouard  2256: #endif
1.126     brouard  2257:   free_vector(xicom,1,n); 
                   2258:   free_vector(pcom,1,n); 
                   2259: } 
                   2260: 
                   2261: 
                   2262: /*************** powell ************************/
1.162     brouard  2263: /*
                   2264: Minimization of a function func of n variables. Input consists of an initial starting point
                   2265: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2266: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2267: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2268: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2269: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2270:  */
1.224     brouard  2271: #ifdef LINMINORIGINAL
                   2272: #else
                   2273:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2274:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2275: #endif
1.126     brouard  2276: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2277:            double (*func)(double [])) 
                   2278: { 
1.224     brouard  2279: #ifdef LINMINORIGINAL
                   2280:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2281:              double (*func)(double [])); 
1.224     brouard  2282: #else 
1.241     brouard  2283:  void linmin(double p[], double xi[], int n, double *fret,
                   2284:             double (*func)(double []),int *flat); 
1.224     brouard  2285: #endif
1.239     brouard  2286:  int i,ibig,j,jk,k; 
1.126     brouard  2287:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2288:   double directest;
1.126     brouard  2289:   double fp,fptt;
                   2290:   double *xits;
                   2291:   int niterf, itmp;
1.224     brouard  2292: #ifdef LINMINORIGINAL
                   2293: #else
                   2294: 
                   2295:   flatdir=ivector(1,n); 
                   2296:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2297: #endif
1.126     brouard  2298: 
                   2299:   pt=vector(1,n); 
                   2300:   ptt=vector(1,n); 
                   2301:   xit=vector(1,n); 
                   2302:   xits=vector(1,n); 
                   2303:   *fret=(*func)(p); 
                   2304:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2305:   rcurr_time = time(NULL);  
1.126     brouard  2306:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2307:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2308:     ibig=0; 
                   2309:     del=0.0; 
1.157     brouard  2310:     rlast_time=rcurr_time;
                   2311:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2312:     rcurr_time = time(NULL);  
                   2313:     curr_time = *localtime(&rcurr_time);
                   2314:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2315:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2316: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2317:     for (i=1;i<=n;i++) {
1.126     brouard  2318:       fprintf(ficrespow," %.12lf", p[i]);
                   2319:     }
1.239     brouard  2320:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2321:     printf("\n#model=  1      +     age ");
                   2322:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2323:     if(nagesqr==1){
1.241     brouard  2324:        printf("  + age*age  ");
                   2325:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2326:     }
                   2327:     for(j=1;j <=ncovmodel-2;j++){
                   2328:       if(Typevar[j]==0) {
                   2329:        printf("  +      V%d  ",Tvar[j]);
                   2330:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2331:       }else if(Typevar[j]==1) {
                   2332:        printf("  +    V%d*age ",Tvar[j]);
                   2333:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2334:       }else if(Typevar[j]==2) {
                   2335:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2336:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2337:       }
                   2338:     }
1.126     brouard  2339:     printf("\n");
1.239     brouard  2340: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2341: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2342:     fprintf(ficlog,"\n");
1.239     brouard  2343:     for(i=1,jk=1; i <=nlstate; i++){
                   2344:       for(k=1; k <=(nlstate+ndeath); k++){
                   2345:        if (k != i) {
                   2346:          printf("%d%d ",i,k);
                   2347:          fprintf(ficlog,"%d%d ",i,k);
                   2348:          for(j=1; j <=ncovmodel; j++){
                   2349:            printf("%12.7f ",p[jk]);
                   2350:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2351:            jk++; 
                   2352:          }
                   2353:          printf("\n");
                   2354:          fprintf(ficlog,"\n");
                   2355:        }
                   2356:       }
                   2357:     }
1.241     brouard  2358:     if(*iter <=3 && *iter >1){
1.157     brouard  2359:       tml = *localtime(&rcurr_time);
                   2360:       strcpy(strcurr,asctime(&tml));
                   2361:       rforecast_time=rcurr_time; 
1.126     brouard  2362:       itmp = strlen(strcurr);
                   2363:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2364:        strcurr[itmp-1]='\0';
1.162     brouard  2365:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2366:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2367:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2368:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2369:        forecast_time = *localtime(&rforecast_time);
                   2370:        strcpy(strfor,asctime(&forecast_time));
                   2371:        itmp = strlen(strfor);
                   2372:        if(strfor[itmp-1]=='\n')
                   2373:          strfor[itmp-1]='\0';
                   2374:        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);
                   2375:        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  2376:       }
                   2377:     }
1.187     brouard  2378:     for (i=1;i<=n;i++) { /* For each direction i */
                   2379:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2380:       fptt=(*fret); 
                   2381: #ifdef DEBUG
1.203     brouard  2382:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2383:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2384: #endif
1.203     brouard  2385:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2386:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2387: #ifdef LINMINORIGINAL
1.188     brouard  2388:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2389: #else
                   2390:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2391:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2392: #endif
                   2393:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2394:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2395:                                /* because that direction will be replaced unless the gain del is small */
                   2396:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2397:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2398:                                /* with the new direction. */
                   2399:                                del=fabs(fptt-(*fret)); 
                   2400:                                ibig=i; 
1.126     brouard  2401:       } 
                   2402: #ifdef DEBUG
                   2403:       printf("%d %.12e",i,(*fret));
                   2404:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2405:       for (j=1;j<=n;j++) {
1.224     brouard  2406:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2407:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2408:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2409:       }
                   2410:       for(j=1;j<=n;j++) {
1.225     brouard  2411:                                printf(" p(%d)=%.12e",j,p[j]);
                   2412:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2413:       }
                   2414:       printf("\n");
                   2415:       fprintf(ficlog,"\n");
                   2416: #endif
1.187     brouard  2417:     } /* end loop on each direction i */
                   2418:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2419:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2420:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2421:       for(j=1;j<=n;j++) {
1.302     brouard  2422:        if(flatdir[j] >0){
                   2423:          printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2424:          fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2425:        }
                   2426:        /* printf("\n"); */
                   2427:        /* fprintf(ficlog,"\n"); */
                   2428:       }
1.243     brouard  2429:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2430:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2431:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2432:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2433:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2434:       /* decreased of more than 3.84  */
                   2435:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2436:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2437:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2438:                        
1.188     brouard  2439:       /* Starting the program with initial values given by a former maximization will simply change */
                   2440:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2441:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2442:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2443: #ifdef DEBUG
                   2444:       int k[2],l;
                   2445:       k[0]=1;
                   2446:       k[1]=-1;
                   2447:       printf("Max: %.12e",(*func)(p));
                   2448:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2449:       for (j=1;j<=n;j++) {
                   2450:        printf(" %.12e",p[j]);
                   2451:        fprintf(ficlog," %.12e",p[j]);
                   2452:       }
                   2453:       printf("\n");
                   2454:       fprintf(ficlog,"\n");
                   2455:       for(l=0;l<=1;l++) {
                   2456:        for (j=1;j<=n;j++) {
                   2457:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2458:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2459:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2460:        }
                   2461:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2462:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2463:       }
                   2464: #endif
                   2465: 
1.224     brouard  2466: #ifdef LINMINORIGINAL
                   2467: #else
                   2468:       free_ivector(flatdir,1,n); 
                   2469: #endif
1.126     brouard  2470:       free_vector(xit,1,n); 
                   2471:       free_vector(xits,1,n); 
                   2472:       free_vector(ptt,1,n); 
                   2473:       free_vector(pt,1,n); 
                   2474:       return; 
1.192     brouard  2475:     } /* enough precision */ 
1.240     brouard  2476:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2477:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2478:       ptt[j]=2.0*p[j]-pt[j]; 
                   2479:       xit[j]=p[j]-pt[j]; 
                   2480:       pt[j]=p[j]; 
                   2481:     } 
1.181     brouard  2482:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2483: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2484:                if (*iter <=4) {
1.225     brouard  2485: #else
                   2486: #endif
1.224     brouard  2487: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2488: #else
1.161     brouard  2489:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2490: #endif
1.162     brouard  2491:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2492:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2493:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2494:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2495:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2496:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2497:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2498:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2499:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2500:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2501:       /* mu² and del² are equal when f3=f1 */
                   2502:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2503:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2504:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2505:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2506: #ifdef NRCORIGINAL
                   2507:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2508: #else
                   2509:       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  2510:       t= t- del*SQR(fp-fptt);
1.183     brouard  2511: #endif
1.202     brouard  2512:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2513: #ifdef DEBUG
1.181     brouard  2514:       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);
                   2515:       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  2516:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2517:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2518:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2519:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2520:       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);
                   2521:       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);
                   2522: #endif
1.183     brouard  2523: #ifdef POWELLORIGINAL
                   2524:       if (t < 0.0) { /* Then we use it for new direction */
                   2525: #else
1.182     brouard  2526:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2527:                                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  2528:         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  2529:         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  2530:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2531:       } 
1.181     brouard  2532:       if (directest < 0.0) { /* Then we use it for new direction */
                   2533: #endif
1.191     brouard  2534: #ifdef DEBUGLINMIN
1.234     brouard  2535:        printf("Before linmin in direction P%d-P0\n",n);
                   2536:        for (j=1;j<=n;j++) {
                   2537:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2538:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2539:          if(j % ncovmodel == 0){
                   2540:            printf("\n");
                   2541:            fprintf(ficlog,"\n");
                   2542:          }
                   2543:        }
1.224     brouard  2544: #endif
                   2545: #ifdef LINMINORIGINAL
1.234     brouard  2546:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2547: #else
1.234     brouard  2548:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2549:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2550: #endif
1.234     brouard  2551:        
1.191     brouard  2552: #ifdef DEBUGLINMIN
1.234     brouard  2553:        for (j=1;j<=n;j++) { 
                   2554:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2555:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2556:          if(j % ncovmodel == 0){
                   2557:            printf("\n");
                   2558:            fprintf(ficlog,"\n");
                   2559:          }
                   2560:        }
1.224     brouard  2561: #endif
1.234     brouard  2562:        for (j=1;j<=n;j++) { 
                   2563:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2564:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2565:        }
1.224     brouard  2566: #ifdef LINMINORIGINAL
                   2567: #else
1.234     brouard  2568:        for (j=1, flatd=0;j<=n;j++) {
                   2569:          if(flatdir[j]>0)
                   2570:            flatd++;
                   2571:        }
                   2572:        if(flatd >0){
1.255     brouard  2573:          printf("%d flat directions: ",flatd);
                   2574:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2575:          for (j=1;j<=n;j++) { 
                   2576:            if(flatdir[j]>0){
                   2577:              printf("%d ",j);
                   2578:              fprintf(ficlog,"%d ",j);
                   2579:            }
                   2580:          }
                   2581:          printf("\n");
                   2582:          fprintf(ficlog,"\n");
                   2583:        }
1.191     brouard  2584: #endif
1.234     brouard  2585:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2586:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2587:        
1.126     brouard  2588: #ifdef DEBUG
1.234     brouard  2589:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2590:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2591:        for(j=1;j<=n;j++){
                   2592:          printf(" %lf",xit[j]);
                   2593:          fprintf(ficlog," %lf",xit[j]);
                   2594:        }
                   2595:        printf("\n");
                   2596:        fprintf(ficlog,"\n");
1.126     brouard  2597: #endif
1.192     brouard  2598:       } /* end of t or directest negative */
1.224     brouard  2599: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2600: #else
1.234     brouard  2601:       } /* end if (fptt < fp)  */
1.192     brouard  2602: #endif
1.225     brouard  2603: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2604:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2605: #else
1.224     brouard  2606: #endif
1.234     brouard  2607:                } /* loop iteration */ 
1.126     brouard  2608: } 
1.234     brouard  2609:   
1.126     brouard  2610: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2611:   
1.235     brouard  2612:   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  2613:   {
1.279     brouard  2614:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2615:      *   (and selected quantitative values in nres)
                   2616:      *  by left multiplying the unit
                   2617:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2618:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2619:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2620:      * or prevalence in state 1, prevalence in state 2, 0
                   2621:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2622:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2623:      * Output is prlim.
                   2624:      * Initial matrix pimij 
                   2625:      */
1.206     brouard  2626:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2627:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2628:   /*  0,                   0                  , 1} */
                   2629:   /*
                   2630:    * and after some iteration: */
                   2631:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2632:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2633:   /*  0,                   0                  , 1} */
                   2634:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2635:   /* {0.51571254859325999, 0.4842874514067399, */
                   2636:   /*  0.51326036147820708, 0.48673963852179264} */
                   2637:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2638:     
1.126     brouard  2639:   int i, ii,j,k;
1.209     brouard  2640:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2641:   /* double **matprod2(); */ /* test */
1.218     brouard  2642:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2643:   double **newm;
1.209     brouard  2644:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2645:   int ncvloop=0;
1.288     brouard  2646:   int first=0;
1.169     brouard  2647:   
1.209     brouard  2648:   min=vector(1,nlstate);
                   2649:   max=vector(1,nlstate);
                   2650:   meandiff=vector(1,nlstate);
                   2651: 
1.218     brouard  2652:        /* Starting with matrix unity */
1.126     brouard  2653:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2654:     for (j=1;j<=nlstate+ndeath;j++){
                   2655:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2656:     }
1.169     brouard  2657:   
                   2658:   cov[1]=1.;
                   2659:   
                   2660:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2661:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2662:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2663:     ncvloop++;
1.126     brouard  2664:     newm=savm;
                   2665:     /* Covariates have to be included here again */
1.138     brouard  2666:     cov[2]=agefin;
1.187     brouard  2667:     if(nagesqr==1)
                   2668:       cov[3]= agefin*agefin;;
1.234     brouard  2669:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2670:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2671:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2672:       /* 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  2673:     }
                   2674:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2675:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2676:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2677:       /* 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  2678:     }
1.237     brouard  2679:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2680:       if(Dummy[Tvar[Tage[k]]]){
                   2681:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2682:       } else{
1.235     brouard  2683:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2684:       }
1.235     brouard  2685:       /* 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  2686:     }
1.237     brouard  2687:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2688:       /* 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  2689:       if(Dummy[Tvard[k][1]==0]){
                   2690:        if(Dummy[Tvard[k][2]==0]){
                   2691:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2692:        }else{
                   2693:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2694:        }
                   2695:       }else{
                   2696:        if(Dummy[Tvard[k][2]==0]){
                   2697:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2698:        }else{
                   2699:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2700:        }
                   2701:       }
1.234     brouard  2702:     }
1.138     brouard  2703:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2704:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2705:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2706:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2707:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2708:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2709:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2710:     
1.126     brouard  2711:     savm=oldm;
                   2712:     oldm=newm;
1.209     brouard  2713: 
                   2714:     for(j=1; j<=nlstate; j++){
                   2715:       max[j]=0.;
                   2716:       min[j]=1.;
                   2717:     }
                   2718:     for(i=1;i<=nlstate;i++){
                   2719:       sumnew=0;
                   2720:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2721:       for(j=1; j<=nlstate; j++){ 
                   2722:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2723:        max[j]=FMAX(max[j],prlim[i][j]);
                   2724:        min[j]=FMIN(min[j],prlim[i][j]);
                   2725:       }
                   2726:     }
                   2727: 
1.126     brouard  2728:     maxmax=0.;
1.209     brouard  2729:     for(j=1; j<=nlstate; j++){
                   2730:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2731:       maxmax=FMAX(maxmax,meandiff[j]);
                   2732:       /* 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  2733:     } /* j loop */
1.203     brouard  2734:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2735:     /* 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  2736:     if(maxmax < ftolpl){
1.209     brouard  2737:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2738:       free_vector(min,1,nlstate);
                   2739:       free_vector(max,1,nlstate);
                   2740:       free_vector(meandiff,1,nlstate);
1.126     brouard  2741:       return prlim;
                   2742:     }
1.288     brouard  2743:   } /* agefin loop */
1.208     brouard  2744:     /* After some age loop it doesn't converge */
1.288     brouard  2745:   if(!first){
                   2746:     first=1;
                   2747:     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);
                   2748:   }
                   2749:   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);
                   2750: 
1.209     brouard  2751:   /* 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); */
                   2752:   free_vector(min,1,nlstate);
                   2753:   free_vector(max,1,nlstate);
                   2754:   free_vector(meandiff,1,nlstate);
1.208     brouard  2755:   
1.169     brouard  2756:   return prlim; /* should not reach here */
1.126     brouard  2757: }
                   2758: 
1.217     brouard  2759: 
                   2760:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2761: 
1.218     brouard  2762:  /* 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) */
                   2763:  /* 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  2764:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2765: {
1.264     brouard  2766:   /* 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  2767:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2768:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2769:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2770:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2771:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2772:   /* Initial matrix pimij */
                   2773:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2774:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2775:   /*  0,                   0                  , 1} */
                   2776:   /*
                   2777:    * and after some iteration: */
                   2778:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2779:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2780:   /*  0,                   0                  , 1} */
                   2781:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2782:   /* {0.51571254859325999, 0.4842874514067399, */
                   2783:   /*  0.51326036147820708, 0.48673963852179264} */
                   2784:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2785: 
                   2786:   int i, ii,j,k;
1.247     brouard  2787:   int first=0;
1.217     brouard  2788:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2789:   /* double **matprod2(); */ /* test */
                   2790:   double **out, cov[NCOVMAX+1], **bmij();
                   2791:   double **newm;
1.218     brouard  2792:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2793:   double        **oldm, **savm;  /* for use */
                   2794: 
1.217     brouard  2795:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2796:   int ncvloop=0;
                   2797:   
                   2798:   min=vector(1,nlstate);
                   2799:   max=vector(1,nlstate);
                   2800:   meandiff=vector(1,nlstate);
                   2801: 
1.266     brouard  2802:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2803:   oldm=oldms; savm=savms;
                   2804:   
                   2805:   /* Starting with matrix unity */
                   2806:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2807:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2808:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2809:     }
                   2810:   
                   2811:   cov[1]=1.;
                   2812:   
                   2813:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2814:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2815:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2816:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2817:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2818:     ncvloop++;
1.218     brouard  2819:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2820:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2821:     /* Covariates have to be included here again */
                   2822:     cov[2]=agefin;
                   2823:     if(nagesqr==1)
                   2824:       cov[3]= agefin*agefin;;
1.242     brouard  2825:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2826:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2827:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2828:       /* 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  2829:     }
                   2830:     /* for (k=1; k<=cptcovn;k++) { */
                   2831:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2832:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2833:     /*   /\* 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])]); *\/ */
                   2834:     /* } */
                   2835:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2836:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2837:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2838:       /* 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]); */
                   2839:     }
                   2840:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2841:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2842:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2843:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2844:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2845:       if(Dummy[Tvar[Tage[k]]]){
                   2846:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2847:       } else{
                   2848:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2849:       }
                   2850:       /* 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]); */
                   2851:     }
                   2852:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2853:       /* 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]); */
                   2854:       if(Dummy[Tvard[k][1]==0]){
                   2855:        if(Dummy[Tvard[k][2]==0]){
                   2856:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2857:        }else{
                   2858:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2859:        }
                   2860:       }else{
                   2861:        if(Dummy[Tvard[k][2]==0]){
                   2862:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2863:        }else{
                   2864:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2865:        }
                   2866:       }
1.217     brouard  2867:     }
                   2868:     
                   2869:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2870:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2871:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2872:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2873:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2874:                /* ij should be linked to the correct index of cov */
                   2875:                /* age and covariate values ij are in 'cov', but we need to pass
                   2876:                 * ij for the observed prevalence at age and status and covariate
                   2877:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2878:                 */
                   2879:     /* 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 *\/ */
                   2880:     /* 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 *\/ */
                   2881:     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  2882:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2883:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2884:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2885:     /*         printf("%d newm= ",i); */
                   2886:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2887:     /*           printf("%f ",newm[i][j]); */
                   2888:     /*         } */
                   2889:     /*         printf("oldm * "); */
                   2890:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2891:     /*           printf("%f ",oldm[i][j]); */
                   2892:     /*         } */
1.268     brouard  2893:     /*         printf(" bmmij "); */
1.266     brouard  2894:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2895:     /*           printf("%f ",pmmij[i][j]); */
                   2896:     /*         } */
                   2897:     /*         printf("\n"); */
                   2898:     /*   } */
                   2899:     /* } */
1.217     brouard  2900:     savm=oldm;
                   2901:     oldm=newm;
1.266     brouard  2902: 
1.217     brouard  2903:     for(j=1; j<=nlstate; j++){
                   2904:       max[j]=0.;
                   2905:       min[j]=1.;
                   2906:     }
                   2907:     for(j=1; j<=nlstate; j++){ 
                   2908:       for(i=1;i<=nlstate;i++){
1.234     brouard  2909:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2910:        bprlim[i][j]= newm[i][j];
                   2911:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2912:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2913:       }
                   2914:     }
1.218     brouard  2915:                
1.217     brouard  2916:     maxmax=0.;
                   2917:     for(i=1; i<=nlstate; i++){
                   2918:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2919:       maxmax=FMAX(maxmax,meandiff[i]);
                   2920:       /* 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  2921:     } /* i loop */
1.217     brouard  2922:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2923:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2924:     if(maxmax < ftolpl){
1.220     brouard  2925:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2926:       free_vector(min,1,nlstate);
                   2927:       free_vector(max,1,nlstate);
                   2928:       free_vector(meandiff,1,nlstate);
                   2929:       return bprlim;
                   2930:     }
1.288     brouard  2931:   } /* agefin loop */
1.217     brouard  2932:     /* After some age loop it doesn't converge */
1.288     brouard  2933:   if(!first){
1.247     brouard  2934:     first=1;
                   2935:     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\
                   2936: 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);
                   2937:   }
                   2938:   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  2939: 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);
                   2940:   /* 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); */
                   2941:   free_vector(min,1,nlstate);
                   2942:   free_vector(max,1,nlstate);
                   2943:   free_vector(meandiff,1,nlstate);
                   2944:   
                   2945:   return bprlim; /* should not reach here */
                   2946: }
                   2947: 
1.126     brouard  2948: /*************** transition probabilities ***************/ 
                   2949: 
                   2950: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2951: {
1.138     brouard  2952:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  2953:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  2954:      model to the ncovmodel covariates (including constant and age).
                   2955:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2956:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2957:      ncth covariate in the global vector x is given by the formula:
                   2958:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2959:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2960:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2961:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  2962:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  2963:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  2964:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  2965:   */
                   2966:   double s1, lnpijopii;
1.126     brouard  2967:   /*double t34;*/
1.164     brouard  2968:   int i,j, nc, ii, jj;
1.126     brouard  2969: 
1.223     brouard  2970:   for(i=1; i<= nlstate; i++){
                   2971:     for(j=1; j<i;j++){
                   2972:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2973:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2974:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2975:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2976:       }
                   2977:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2978:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2979:     }
                   2980:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2981:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2982:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2983:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2984:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2985:       }
                   2986:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2987:     }
                   2988:   }
1.218     brouard  2989:   
1.223     brouard  2990:   for(i=1; i<= nlstate; i++){
                   2991:     s1=0;
                   2992:     for(j=1; j<i; j++){
                   2993:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2994:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2995:     }
                   2996:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2997:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2998:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2999:     }
                   3000:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3001:     ps[i][i]=1./(s1+1.);
                   3002:     /* Computing other pijs */
                   3003:     for(j=1; j<i; j++)
                   3004:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3005:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3006:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3007:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3008:   } /* end i */
1.218     brouard  3009:   
1.223     brouard  3010:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3011:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3012:       ps[ii][jj]=0;
                   3013:       ps[ii][ii]=1;
                   3014:     }
                   3015:   }
1.294     brouard  3016: 
                   3017: 
1.223     brouard  3018:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3019:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3020:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3021:   /*   } */
                   3022:   /*   printf("\n "); */
                   3023:   /* } */
                   3024:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3025:   /*
                   3026:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3027:                goto end;*/
1.266     brouard  3028:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3029: }
                   3030: 
1.218     brouard  3031: /*************** backward transition probabilities ***************/ 
                   3032: 
                   3033:  /* 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 ) */
                   3034: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3035:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3036: {
1.302     brouard  3037:   /* 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  3038:    * 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  3039:    */
1.218     brouard  3040:   int i, ii, j,k;
1.222     brouard  3041:   
                   3042:   double **out, **pmij();
                   3043:   double sumnew=0.;
1.218     brouard  3044:   double agefin;
1.292     brouard  3045:   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  3046:   double **dnewm, **dsavm, **doldm;
                   3047:   double **bbmij;
                   3048:   
1.218     brouard  3049:   doldm=ddoldms; /* global pointers */
1.222     brouard  3050:   dnewm=ddnewms;
                   3051:   dsavm=ddsavms;
                   3052:   
                   3053:   agefin=cov[2];
1.268     brouard  3054:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3055:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3056:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3057:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3058: 
                   3059:   /* P_x */
1.266     brouard  3060:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3061:   /* outputs pmmij which is a stochastic matrix in row */
                   3062: 
                   3063:   /* Diag(w_x) */
1.292     brouard  3064:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3065:   sumnew=0.;
1.269     brouard  3066:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3067:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3068:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3069:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3070:   }
                   3071:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3072:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3073:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3074:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3075:     }
                   3076:   }else{
                   3077:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3078:       for (j=1;j<=nlstate+ndeath;j++)
                   3079:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3080:     }
                   3081:     /* if(sumnew <0.9){ */
                   3082:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3083:     /* } */
                   3084:   }
                   3085:   k3=0.0;  /* We put the last diagonal to 0 */
                   3086:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3087:       doldm[ii][ii]= k3;
                   3088:   }
                   3089:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3090:   
1.292     brouard  3091:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3092:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3093: 
1.292     brouard  3094:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3095:   /* 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  3096:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3097:     sumnew=0.;
1.222     brouard  3098:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3099:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3100:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3101:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3102:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3103:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3104:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3105:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3106:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3107:        /* }else */
1.268     brouard  3108:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3109:     } /*End ii */
                   3110:   } /* 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 */
                   3111: 
1.292     brouard  3112:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3113:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3114:   /* end bmij */
1.266     brouard  3115:   return ps; /*pointer is unchanged */
1.218     brouard  3116: }
1.217     brouard  3117: /*************** transition probabilities ***************/ 
                   3118: 
1.218     brouard  3119: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3120: {
                   3121:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3122:      computes the probability to be observed in state j being in state i by appying the
                   3123:      model to the ncovmodel covariates (including constant and age).
                   3124:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3125:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3126:      ncth covariate in the global vector x is given by the formula:
                   3127:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3128:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3129:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3130:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3131:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3132:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3133:   */
                   3134:   double s1, lnpijopii;
                   3135:   /*double t34;*/
                   3136:   int i,j, nc, ii, jj;
                   3137: 
1.234     brouard  3138:   for(i=1; i<= nlstate; i++){
                   3139:     for(j=1; j<i;j++){
                   3140:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3141:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3142:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3143:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3144:       }
                   3145:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3146:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3147:     }
                   3148:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3149:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3150:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3151:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3152:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3153:       }
                   3154:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3155:     }
                   3156:   }
                   3157:   
                   3158:   for(i=1; i<= nlstate; i++){
                   3159:     s1=0;
                   3160:     for(j=1; j<i; j++){
                   3161:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3162:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3163:     }
                   3164:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3165:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3166:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3167:     }
                   3168:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3169:     ps[i][i]=1./(s1+1.);
                   3170:     /* Computing other pijs */
                   3171:     for(j=1; j<i; j++)
                   3172:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3173:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3174:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3175:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3176:   } /* end i */
                   3177:   
                   3178:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3179:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3180:       ps[ii][jj]=0;
                   3181:       ps[ii][ii]=1;
                   3182:     }
                   3183:   }
1.296     brouard  3184:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3185:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3186:     s1=0.;
                   3187:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3188:       s1+=ps[ii][jj];
                   3189:     }
                   3190:     for(ii=1; ii<= nlstate; ii++){
                   3191:       ps[ii][jj]=ps[ii][jj]/s1;
                   3192:     }
                   3193:   }
                   3194:   /* Transposition */
                   3195:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3196:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3197:       s1=ps[ii][jj];
                   3198:       ps[ii][jj]=ps[jj][ii];
                   3199:       ps[jj][ii]=s1;
                   3200:     }
                   3201:   }
                   3202:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3203:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3204:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3205:   /*   } */
                   3206:   /*   printf("\n "); */
                   3207:   /* } */
                   3208:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3209:   /*
                   3210:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3211:     goto end;*/
                   3212:   return ps;
1.217     brouard  3213: }
                   3214: 
                   3215: 
1.126     brouard  3216: /**************** Product of 2 matrices ******************/
                   3217: 
1.145     brouard  3218: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3219: {
                   3220:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3221:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3222:   /* in, b, out are matrice of pointers which should have been initialized 
                   3223:      before: only the contents of out is modified. The function returns
                   3224:      a pointer to pointers identical to out */
1.145     brouard  3225:   int i, j, k;
1.126     brouard  3226:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3227:     for(k=ncolol; k<=ncoloh; k++){
                   3228:       out[i][k]=0.;
                   3229:       for(j=ncl; j<=nch; j++)
                   3230:        out[i][k] +=in[i][j]*b[j][k];
                   3231:     }
1.126     brouard  3232:   return out;
                   3233: }
                   3234: 
                   3235: 
                   3236: /************* Higher Matrix Product ***************/
                   3237: 
1.235     brouard  3238: 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  3239: {
1.218     brouard  3240:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3241:      'nhstepm*hstepm*stepm' months (i.e. until
                   3242:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3243:      nhstepm*hstepm matrices. 
                   3244:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3245:      (typically every 2 years instead of every month which is too big 
                   3246:      for the memory).
                   3247:      Model is determined by parameters x and covariates have to be 
                   3248:      included manually here. 
                   3249: 
                   3250:      */
                   3251: 
                   3252:   int i, j, d, h, k;
1.131     brouard  3253:   double **out, cov[NCOVMAX+1];
1.126     brouard  3254:   double **newm;
1.187     brouard  3255:   double agexact;
1.214     brouard  3256:   double agebegin, ageend;
1.126     brouard  3257: 
                   3258:   /* Hstepm could be zero and should return the unit matrix */
                   3259:   for (i=1;i<=nlstate+ndeath;i++)
                   3260:     for (j=1;j<=nlstate+ndeath;j++){
                   3261:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3262:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3263:     }
                   3264:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3265:   for(h=1; h <=nhstepm; h++){
                   3266:     for(d=1; d <=hstepm; d++){
                   3267:       newm=savm;
                   3268:       /* Covariates have to be included here again */
                   3269:       cov[1]=1.;
1.214     brouard  3270:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3271:       cov[2]=agexact;
                   3272:       if(nagesqr==1)
1.227     brouard  3273:        cov[3]= agexact*agexact;
1.235     brouard  3274:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3275:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3276:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3277:        /* 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)); */
                   3278:       }
                   3279:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3280:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3281:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3282:        /* 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]); */
                   3283:       }
                   3284:       for (k=1; k<=cptcovage;k++){
                   3285:        if(Dummy[Tvar[Tage[k]]]){
                   3286:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3287:        } else{
                   3288:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3289:        }
                   3290:        /* 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]); */
                   3291:       }
                   3292:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3293:        /* 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]); */
                   3294:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3295:       }
                   3296:       /* for (k=1; k<=cptcovn;k++)  */
                   3297:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3298:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3299:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3300:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3301:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3302:       
                   3303:       
1.126     brouard  3304:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3305:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3306:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3307:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3308:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3309:       /* if((int)age == 70){ */
                   3310:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3311:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3312:       /*         printf("%d pmmij ",i); */
                   3313:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3314:       /*           printf("%f ",pmmij[i][j]); */
                   3315:       /*         } */
                   3316:       /*         printf(" oldm "); */
                   3317:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3318:       /*           printf("%f ",oldm[i][j]); */
                   3319:       /*         } */
                   3320:       /*         printf("\n"); */
                   3321:       /*       } */
                   3322:       /* } */
1.126     brouard  3323:       savm=oldm;
                   3324:       oldm=newm;
                   3325:     }
                   3326:     for(i=1; i<=nlstate+ndeath; i++)
                   3327:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3328:        po[i][j][h]=newm[i][j];
                   3329:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3330:       }
1.128     brouard  3331:     /*printf("h=%d ",h);*/
1.126     brouard  3332:   } /* end h */
1.267     brouard  3333:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3334:   return po;
                   3335: }
                   3336: 
1.217     brouard  3337: /************* Higher Back Matrix Product ***************/
1.218     brouard  3338: /* 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  3339: 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  3340: {
1.266     brouard  3341:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3342:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3343:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3344:      nhstepm*hstepm matrices.
                   3345:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3346:      (typically every 2 years instead of every month which is too big
1.217     brouard  3347:      for the memory).
1.218     brouard  3348:      Model is determined by parameters x and covariates have to be
1.266     brouard  3349:      included manually here. Then we use a call to bmij(x and cov)
                   3350:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3351:   */
1.217     brouard  3352: 
                   3353:   int i, j, d, h, k;
1.266     brouard  3354:   double **out, cov[NCOVMAX+1], **bmij();
                   3355:   double **newm, ***newmm;
1.217     brouard  3356:   double agexact;
                   3357:   double agebegin, ageend;
1.222     brouard  3358:   double **oldm, **savm;
1.217     brouard  3359: 
1.266     brouard  3360:   newmm=po; /* To be saved */
                   3361:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3362:   /* Hstepm could be zero and should return the unit matrix */
                   3363:   for (i=1;i<=nlstate+ndeath;i++)
                   3364:     for (j=1;j<=nlstate+ndeath;j++){
                   3365:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3366:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3367:     }
                   3368:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3369:   for(h=1; h <=nhstepm; h++){
                   3370:     for(d=1; d <=hstepm; d++){
                   3371:       newm=savm;
                   3372:       /* Covariates have to be included here again */
                   3373:       cov[1]=1.;
1.271     brouard  3374:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3375:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3376:       cov[2]=agexact;
                   3377:       if(nagesqr==1)
1.222     brouard  3378:        cov[3]= agexact*agexact;
1.266     brouard  3379:       for (k=1; k<=cptcovn;k++){
                   3380:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3381:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3382:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3383:         /* 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)); */
                   3384:       }
1.267     brouard  3385:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3386:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3387:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3388:        /* 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]); */
                   3389:       }
                   3390:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3391:        if(Dummy[Tvar[Tage[k]]]){
                   3392:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3393:        } else{
                   3394:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3395:        }
                   3396:        /* 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]); */
                   3397:       }
                   3398:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3399:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3400:       }                        
1.217     brouard  3401:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3402:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3403: 
1.218     brouard  3404:       /* Careful transposed matrix */
1.266     brouard  3405:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3406:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3407:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3408:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3409:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3410:       /* if((int)age == 70){ */
                   3411:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3412:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3413:       /*         printf("%d pmmij ",i); */
                   3414:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3415:       /*           printf("%f ",pmmij[i][j]); */
                   3416:       /*         } */
                   3417:       /*         printf(" oldm "); */
                   3418:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3419:       /*           printf("%f ",oldm[i][j]); */
                   3420:       /*         } */
                   3421:       /*         printf("\n"); */
                   3422:       /*       } */
                   3423:       /* } */
                   3424:       savm=oldm;
                   3425:       oldm=newm;
                   3426:     }
                   3427:     for(i=1; i<=nlstate+ndeath; i++)
                   3428:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3429:        po[i][j][h]=newm[i][j];
1.268     brouard  3430:        /* if(h==nhstepm) */
                   3431:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3432:       }
1.268     brouard  3433:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3434:   } /* end h */
1.268     brouard  3435:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3436:   return po;
                   3437: }
                   3438: 
                   3439: 
1.162     brouard  3440: #ifdef NLOPT
                   3441:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3442:   double fret;
                   3443:   double *xt;
                   3444:   int j;
                   3445:   myfunc_data *d2 = (myfunc_data *) pd;
                   3446: /* xt = (p1-1); */
                   3447:   xt=vector(1,n); 
                   3448:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3449: 
                   3450:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3451:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3452:   printf("Function = %.12lf ",fret);
                   3453:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3454:   printf("\n");
                   3455:  free_vector(xt,1,n);
                   3456:   return fret;
                   3457: }
                   3458: #endif
1.126     brouard  3459: 
                   3460: /*************** log-likelihood *************/
                   3461: double func( double *x)
                   3462: {
1.226     brouard  3463:   int i, ii, j, k, mi, d, kk;
                   3464:   int ioffset=0;
                   3465:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3466:   double **out;
                   3467:   double lli; /* Individual log likelihood */
                   3468:   int s1, s2;
1.228     brouard  3469:   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  3470:   double bbh, survp;
                   3471:   long ipmx;
                   3472:   double agexact;
                   3473:   /*extern weight */
                   3474:   /* We are differentiating ll according to initial status */
                   3475:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3476:   /*for(i=1;i<imx;i++) 
                   3477:     printf(" %d\n",s[4][i]);
                   3478:   */
1.162     brouard  3479: 
1.226     brouard  3480:   ++countcallfunc;
1.162     brouard  3481: 
1.226     brouard  3482:   cov[1]=1.;
1.126     brouard  3483: 
1.226     brouard  3484:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3485:   ioffset=0;
1.226     brouard  3486:   if(mle==1){
                   3487:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3488:       /* Computes the values of the ncovmodel covariates of the model
                   3489:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3490:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3491:         to be observed in j being in i according to the model.
                   3492:       */
1.243     brouard  3493:       ioffset=2+nagesqr ;
1.233     brouard  3494:    /* Fixed */
1.234     brouard  3495:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3496:        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)*/
                   3497:       }
1.226     brouard  3498:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3499:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3500:         has been calculated etc */
                   3501:       /* For an individual i, wav[i] gives the number of effective waves */
                   3502:       /* We compute the contribution to Likelihood of each effective transition
                   3503:         mw[mi][i] is real wave of the mi th effectve wave */
                   3504:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3505:         s2=s[mw[mi+1][i]][i];
                   3506:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3507:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3508:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3509:       */
                   3510:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3511:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3512:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3513:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3514:        }
                   3515:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3516:          for (j=1;j<=nlstate+ndeath;j++){
                   3517:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3518:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3519:          }
                   3520:        for(d=0; d<dh[mi][i]; d++){
                   3521:          newm=savm;
                   3522:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3523:          cov[2]=agexact;
                   3524:          if(nagesqr==1)
                   3525:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3526:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3527:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3528:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3529:          else
                   3530:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3531:          }
                   3532:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3533:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3534:          savm=oldm;
                   3535:          oldm=newm;
                   3536:        } /* end mult */
                   3537:        
                   3538:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3539:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3540:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3541:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3542:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3543:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3544:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3545:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3546:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3547:                                 * -stepm/2 to stepm/2 .
                   3548:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3549:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3550:                                 */
1.234     brouard  3551:        s1=s[mw[mi][i]][i];
                   3552:        s2=s[mw[mi+1][i]][i];
                   3553:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3554:        /* bias bh is positive if real duration
                   3555:         * is higher than the multiple of stepm and negative otherwise.
                   3556:         */
                   3557:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3558:        if( s2 > nlstate){ 
                   3559:          /* i.e. if s2 is a death state and if the date of death is known 
                   3560:             then the contribution to the likelihood is the probability to 
                   3561:             die between last step unit time and current  step unit time, 
                   3562:             which is also equal to probability to die before dh 
                   3563:             minus probability to die before dh-stepm . 
                   3564:             In version up to 0.92 likelihood was computed
                   3565:             as if date of death was unknown. Death was treated as any other
                   3566:             health state: the date of the interview describes the actual state
                   3567:             and not the date of a change in health state. The former idea was
                   3568:             to consider that at each interview the state was recorded
                   3569:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3570:             introduced the exact date of death then we should have modified
                   3571:             the contribution of an exact death to the likelihood. This new
                   3572:             contribution is smaller and very dependent of the step unit
                   3573:             stepm. It is no more the probability to die between last interview
                   3574:             and month of death but the probability to survive from last
                   3575:             interview up to one month before death multiplied by the
                   3576:             probability to die within a month. Thanks to Chris
                   3577:             Jackson for correcting this bug.  Former versions increased
                   3578:             mortality artificially. The bad side is that we add another loop
                   3579:             which slows down the processing. The difference can be up to 10%
                   3580:             lower mortality.
                   3581:          */
                   3582:          /* If, at the beginning of the maximization mostly, the
                   3583:             cumulative probability or probability to be dead is
                   3584:             constant (ie = 1) over time d, the difference is equal to
                   3585:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3586:             s1 at precedent wave, to be dead a month before current
                   3587:             wave is equal to probability, being at state s1 at
                   3588:             precedent wave, to be dead at mont of the current
                   3589:             wave. Then the observed probability (that this person died)
                   3590:             is null according to current estimated parameter. In fact,
                   3591:             it should be very low but not zero otherwise the log go to
                   3592:             infinity.
                   3593:          */
1.183     brouard  3594: /* #ifdef INFINITYORIGINAL */
                   3595: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3596: /* #else */
                   3597: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3598: /*         lli=log(mytinydouble); */
                   3599: /*       else */
                   3600: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3601: /* #endif */
1.226     brouard  3602:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3603:          
1.226     brouard  3604:        } else if  ( s2==-1 ) { /* alive */
                   3605:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3606:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3607:          /*survp += out[s1][j]; */
                   3608:          lli= log(survp);
                   3609:        }
                   3610:        else if  (s2==-4) { 
                   3611:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3612:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3613:          lli= log(survp); 
                   3614:        } 
                   3615:        else if  (s2==-5) { 
                   3616:          for (j=1,survp=0. ; j<=2; j++)  
                   3617:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3618:          lli= log(survp); 
                   3619:        } 
                   3620:        else{
                   3621:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3622:          /*  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 */
                   3623:        } 
                   3624:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3625:        /*if(lli ==000.0)*/
                   3626:        /*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); */
                   3627:        ipmx +=1;
                   3628:        sw += weight[i];
                   3629:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3630:        /* if (lli < log(mytinydouble)){ */
                   3631:        /*   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); */
                   3632:        /*   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]); */
                   3633:        /* } */
                   3634:       } /* end of wave */
                   3635:     } /* end of individual */
                   3636:   }  else if(mle==2){
                   3637:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3638:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3639:       for(mi=1; mi<= wav[i]-1; mi++){
                   3640:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3641:          for (j=1;j<=nlstate+ndeath;j++){
                   3642:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3643:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3644:          }
                   3645:        for(d=0; d<=dh[mi][i]; d++){
                   3646:          newm=savm;
                   3647:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3648:          cov[2]=agexact;
                   3649:          if(nagesqr==1)
                   3650:            cov[3]= agexact*agexact;
                   3651:          for (kk=1; kk<=cptcovage;kk++) {
                   3652:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3653:          }
                   3654:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3655:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3656:          savm=oldm;
                   3657:          oldm=newm;
                   3658:        } /* end mult */
                   3659:       
                   3660:        s1=s[mw[mi][i]][i];
                   3661:        s2=s[mw[mi+1][i]][i];
                   3662:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3663:        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 */
                   3664:        ipmx +=1;
                   3665:        sw += weight[i];
                   3666:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3667:       } /* end of wave */
                   3668:     } /* end of individual */
                   3669:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3670:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3671:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3672:       for(mi=1; mi<= wav[i]-1; mi++){
                   3673:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3674:          for (j=1;j<=nlstate+ndeath;j++){
                   3675:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3676:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3677:          }
                   3678:        for(d=0; d<dh[mi][i]; d++){
                   3679:          newm=savm;
                   3680:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3681:          cov[2]=agexact;
                   3682:          if(nagesqr==1)
                   3683:            cov[3]= agexact*agexact;
                   3684:          for (kk=1; kk<=cptcovage;kk++) {
                   3685:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3686:          }
                   3687:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3688:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3689:          savm=oldm;
                   3690:          oldm=newm;
                   3691:        } /* end mult */
                   3692:       
                   3693:        s1=s[mw[mi][i]][i];
                   3694:        s2=s[mw[mi+1][i]][i];
                   3695:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3696:        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 */
                   3697:        ipmx +=1;
                   3698:        sw += weight[i];
                   3699:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3700:       } /* end of wave */
                   3701:     } /* end of individual */
                   3702:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3703:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3704:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3705:       for(mi=1; mi<= wav[i]-1; mi++){
                   3706:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3707:          for (j=1;j<=nlstate+ndeath;j++){
                   3708:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3709:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3710:          }
                   3711:        for(d=0; d<dh[mi][i]; d++){
                   3712:          newm=savm;
                   3713:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3714:          cov[2]=agexact;
                   3715:          if(nagesqr==1)
                   3716:            cov[3]= agexact*agexact;
                   3717:          for (kk=1; kk<=cptcovage;kk++) {
                   3718:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3719:          }
1.126     brouard  3720:        
1.226     brouard  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:        if( s2 > nlstate){ 
                   3730:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3731:        } else if  ( s2==-1 ) { /* alive */
                   3732:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3733:            survp += out[s1][j];
                   3734:          lli= log(survp);
                   3735:        }else{
                   3736:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3737:        }
                   3738:        ipmx +=1;
                   3739:        sw += weight[i];
                   3740:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3741: /*     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  3742:       } /* end of wave */
                   3743:     } /* end of individual */
                   3744:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3745:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3746:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3747:       for(mi=1; mi<= wav[i]-1; mi++){
                   3748:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3749:          for (j=1;j<=nlstate+ndeath;j++){
                   3750:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3751:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3752:          }
                   3753:        for(d=0; d<dh[mi][i]; d++){
                   3754:          newm=savm;
                   3755:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3756:          cov[2]=agexact;
                   3757:          if(nagesqr==1)
                   3758:            cov[3]= agexact*agexact;
                   3759:          for (kk=1; kk<=cptcovage;kk++) {
                   3760:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3761:          }
1.126     brouard  3762:        
1.226     brouard  3763:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3764:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3765:          savm=oldm;
                   3766:          oldm=newm;
                   3767:        } /* end mult */
                   3768:       
                   3769:        s1=s[mw[mi][i]][i];
                   3770:        s2=s[mw[mi+1][i]][i];
                   3771:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3772:        ipmx +=1;
                   3773:        sw += weight[i];
                   3774:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3775:        /*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]);*/
                   3776:       } /* end of wave */
                   3777:     } /* end of individual */
                   3778:   } /* End of if */
                   3779:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3780:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3781:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3782:   return -l;
1.126     brouard  3783: }
                   3784: 
                   3785: /*************** log-likelihood *************/
                   3786: double funcone( double *x)
                   3787: {
1.228     brouard  3788:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3789:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3790:   int ioffset=0;
1.131     brouard  3791:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3792:   double **out;
                   3793:   double lli; /* Individual log likelihood */
                   3794:   double llt;
                   3795:   int s1, s2;
1.228     brouard  3796:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3797: 
1.126     brouard  3798:   double bbh, survp;
1.187     brouard  3799:   double agexact;
1.214     brouard  3800:   double agebegin, ageend;
1.126     brouard  3801:   /*extern weight */
                   3802:   /* We are differentiating ll according to initial status */
                   3803:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3804:   /*for(i=1;i<imx;i++) 
                   3805:     printf(" %d\n",s[4][i]);
                   3806:   */
                   3807:   cov[1]=1.;
                   3808: 
                   3809:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3810:   ioffset=0;
                   3811:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3812:     /* ioffset=2+nagesqr+cptcovage; */
                   3813:     ioffset=2+nagesqr;
1.232     brouard  3814:     /* Fixed */
1.224     brouard  3815:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3816:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3817:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3818:       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)*/
                   3819: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3820: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3821: /*    cov[2+6]=covar[2][i]; V2  */
                   3822: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3823: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3824: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3825: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3826: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3827: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3828:     }
1.232     brouard  3829:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3830:     /*   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?)*\/ */
                   3831:     /* } */
1.231     brouard  3832:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3833:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3834:     /* } */
1.225     brouard  3835:     
1.233     brouard  3836: 
                   3837:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3838:     /* Wave varying (but not age varying) */
                   3839:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3840:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3841:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3842:       }
1.232     brouard  3843:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3844:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3845:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3846:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3847:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3848:       /* 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  3849:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3850:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3851:       /*       /\* 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]); *\/ */
                   3852:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3853:       /* } */
1.126     brouard  3854:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3855:        for (j=1;j<=nlstate+ndeath;j++){
                   3856:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3857:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3858:        }
1.214     brouard  3859:       
                   3860:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3861:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3862:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3863:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3864:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3865:          and mw[mi+1][i]. dh depends on stepm.*/
                   3866:        newm=savm;
1.247     brouard  3867:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3868:        cov[2]=agexact;
                   3869:        if(nagesqr==1)
                   3870:          cov[3]= agexact*agexact;
                   3871:        for (kk=1; kk<=cptcovage;kk++) {
                   3872:          if(!FixedV[Tvar[Tage[kk]]])
                   3873:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3874:          else
                   3875:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3876:        }
                   3877:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3878:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3879:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3880:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3881:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3882:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3883:        savm=oldm;
                   3884:        oldm=newm;
1.126     brouard  3885:       } /* end mult */
                   3886:       
                   3887:       s1=s[mw[mi][i]][i];
                   3888:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3889:       /* if(s2==-1){ */
1.268     brouard  3890:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3891:       /*       /\* exit(1); *\/ */
                   3892:       /* } */
1.126     brouard  3893:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3894:       /* bias is positive if real duration
                   3895:        * is higher than the multiple of stepm and negative otherwise.
                   3896:        */
                   3897:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3898:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3899:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3900:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3901:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3902:        lli= log(survp);
1.126     brouard  3903:       }else if (mle==1){
1.242     brouard  3904:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3905:       } else if(mle==2){
1.242     brouard  3906:        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  3907:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3908:        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  3909:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3910:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3911:       } else{  /* mle=0 back to 1 */
1.242     brouard  3912:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3913:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3914:       } /* End of if */
                   3915:       ipmx +=1;
                   3916:       sw += weight[i];
                   3917:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3918:       /*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  3919:       if(globpr){
1.246     brouard  3920:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3921:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3922:                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  3923:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3924:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3925:          llt +=ll[k]*gipmx/gsw;
                   3926:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3927:        }
                   3928:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3929:       }
1.232     brouard  3930:        } /* end of wave */
                   3931: } /* end of individual */
                   3932: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3933: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3934: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3935: if(globpr==0){ /* First time we count the contributions and weights */
                   3936:        gipmx=ipmx;
                   3937:        gsw=sw;
                   3938: }
                   3939: return -l;
1.126     brouard  3940: }
                   3941: 
                   3942: 
                   3943: /*************** function likelione ***********/
1.292     brouard  3944: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  3945: {
                   3946:   /* This routine should help understanding what is done with 
                   3947:      the selection of individuals/waves and
                   3948:      to check the exact contribution to the likelihood.
                   3949:      Plotting could be done.
                   3950:    */
                   3951:   int k;
                   3952: 
                   3953:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3954:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3955:     strcat(fileresilk,fileresu);
1.126     brouard  3956:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3957:       printf("Problem with resultfile: %s\n", fileresilk);
                   3958:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3959:     }
1.214     brouard  3960:     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");
                   3961:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3962:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3963:     for(k=1; k<=nlstate; k++) 
                   3964:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3965:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3966:   }
                   3967: 
1.292     brouard  3968:   *fretone=(*func)(p);
1.126     brouard  3969:   if(*globpri !=0){
                   3970:     fclose(ficresilk);
1.205     brouard  3971:     if (mle ==0)
                   3972:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3973:     else if(mle >=1)
                   3974:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3975:     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  3976:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  3977:       
                   3978:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3979:       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  3980: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3981:     }
1.207     brouard  3982:     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  3983: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3984:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3985: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3986:     fflush(fichtm);
1.205     brouard  3987:   }
1.126     brouard  3988:   return;
                   3989: }
                   3990: 
                   3991: 
                   3992: /*********** Maximum Likelihood Estimation ***************/
                   3993: 
                   3994: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3995: {
1.165     brouard  3996:   int i,j, iter=0;
1.126     brouard  3997:   double **xi;
                   3998:   double fret;
                   3999:   double fretone; /* Only one call to likelihood */
                   4000:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4001: 
                   4002: #ifdef NLOPT
                   4003:   int creturn;
                   4004:   nlopt_opt opt;
                   4005:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4006:   double *lb;
                   4007:   double minf; /* the minimum objective value, upon return */
                   4008:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4009:   myfunc_data dinst, *d = &dinst;
                   4010: #endif
                   4011: 
                   4012: 
1.126     brouard  4013:   xi=matrix(1,npar,1,npar);
                   4014:   for (i=1;i<=npar;i++)
                   4015:     for (j=1;j<=npar;j++)
                   4016:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4017:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4018:   strcpy(filerespow,"POW_"); 
1.126     brouard  4019:   strcat(filerespow,fileres);
                   4020:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4021:     printf("Problem with resultfile: %s\n", filerespow);
                   4022:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4023:   }
                   4024:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4025:   for (i=1;i<=nlstate;i++)
                   4026:     for(j=1;j<=nlstate+ndeath;j++)
                   4027:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4028:   fprintf(ficrespow,"\n");
1.162     brouard  4029: #ifdef POWELL
1.126     brouard  4030:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4031: #endif
1.126     brouard  4032: 
1.162     brouard  4033: #ifdef NLOPT
                   4034: #ifdef NEWUOA
                   4035:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4036: #else
                   4037:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4038: #endif
                   4039:   lb=vector(0,npar-1);
                   4040:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4041:   nlopt_set_lower_bounds(opt, lb);
                   4042:   nlopt_set_initial_step1(opt, 0.1);
                   4043:   
                   4044:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4045:   d->function = func;
                   4046:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4047:   nlopt_set_min_objective(opt, myfunc, d);
                   4048:   nlopt_set_xtol_rel(opt, ftol);
                   4049:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4050:     printf("nlopt failed! %d\n",creturn); 
                   4051:   }
                   4052:   else {
                   4053:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4054:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4055:     iter=1; /* not equal */
                   4056:   }
                   4057:   nlopt_destroy(opt);
                   4058: #endif
1.126     brouard  4059:   free_matrix(xi,1,npar,1,npar);
                   4060:   fclose(ficrespow);
1.203     brouard  4061:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4062:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4063:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4064: 
                   4065: }
                   4066: 
                   4067: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4068: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4069: {
                   4070:   double  **a,**y,*x,pd;
1.203     brouard  4071:   /* double **hess; */
1.164     brouard  4072:   int i, j;
1.126     brouard  4073:   int *indx;
                   4074: 
                   4075:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4076:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4077:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4078:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4079:   double gompertz(double p[]);
1.203     brouard  4080:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4081: 
                   4082:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4083:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4084:   for (i=1;i<=npar;i++){
1.203     brouard  4085:     printf("%d-",i);fflush(stdout);
                   4086:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4087:    
                   4088:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4089:     
                   4090:     /*  printf(" %f ",p[i]);
                   4091:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4092:   }
                   4093:   
                   4094:   for (i=1;i<=npar;i++) {
                   4095:     for (j=1;j<=npar;j++)  {
                   4096:       if (j>i) { 
1.203     brouard  4097:        printf(".%d-%d",i,j);fflush(stdout);
                   4098:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4099:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4100:        
                   4101:        hess[j][i]=hess[i][j];    
                   4102:        /*printf(" %lf ",hess[i][j]);*/
                   4103:       }
                   4104:     }
                   4105:   }
                   4106:   printf("\n");
                   4107:   fprintf(ficlog,"\n");
                   4108: 
                   4109:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4110:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4111:   
                   4112:   a=matrix(1,npar,1,npar);
                   4113:   y=matrix(1,npar,1,npar);
                   4114:   x=vector(1,npar);
                   4115:   indx=ivector(1,npar);
                   4116:   for (i=1;i<=npar;i++)
                   4117:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4118:   ludcmp(a,npar,indx,&pd);
                   4119: 
                   4120:   for (j=1;j<=npar;j++) {
                   4121:     for (i=1;i<=npar;i++) x[i]=0;
                   4122:     x[j]=1;
                   4123:     lubksb(a,npar,indx,x);
                   4124:     for (i=1;i<=npar;i++){ 
                   4125:       matcov[i][j]=x[i];
                   4126:     }
                   4127:   }
                   4128: 
                   4129:   printf("\n#Hessian matrix#\n");
                   4130:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4131:   for (i=1;i<=npar;i++) { 
                   4132:     for (j=1;j<=npar;j++) { 
1.203     brouard  4133:       printf("%.6e ",hess[i][j]);
                   4134:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4135:     }
                   4136:     printf("\n");
                   4137:     fprintf(ficlog,"\n");
                   4138:   }
                   4139: 
1.203     brouard  4140:   /* printf("\n#Covariance matrix#\n"); */
                   4141:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4142:   /* for (i=1;i<=npar;i++) {  */
                   4143:   /*   for (j=1;j<=npar;j++) {  */
                   4144:   /*     printf("%.6e ",matcov[i][j]); */
                   4145:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4146:   /*   } */
                   4147:   /*   printf("\n"); */
                   4148:   /*   fprintf(ficlog,"\n"); */
                   4149:   /* } */
                   4150: 
1.126     brouard  4151:   /* Recompute Inverse */
1.203     brouard  4152:   /* for (i=1;i<=npar;i++) */
                   4153:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4154:   /* ludcmp(a,npar,indx,&pd); */
                   4155: 
                   4156:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4157: 
                   4158:   /* for (j=1;j<=npar;j++) { */
                   4159:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4160:   /*   x[j]=1; */
                   4161:   /*   lubksb(a,npar,indx,x); */
                   4162:   /*   for (i=1;i<=npar;i++){  */
                   4163:   /*     y[i][j]=x[i]; */
                   4164:   /*     printf("%.3e ",y[i][j]); */
                   4165:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4166:   /*   } */
                   4167:   /*   printf("\n"); */
                   4168:   /*   fprintf(ficlog,"\n"); */
                   4169:   /* } */
                   4170: 
                   4171:   /* Verifying the inverse matrix */
                   4172: #ifdef DEBUGHESS
                   4173:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4174: 
1.203     brouard  4175:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4176:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4177: 
                   4178:   for (j=1;j<=npar;j++) {
                   4179:     for (i=1;i<=npar;i++){ 
1.203     brouard  4180:       printf("%.2f ",y[i][j]);
                   4181:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4182:     }
                   4183:     printf("\n");
                   4184:     fprintf(ficlog,"\n");
                   4185:   }
1.203     brouard  4186: #endif
1.126     brouard  4187: 
                   4188:   free_matrix(a,1,npar,1,npar);
                   4189:   free_matrix(y,1,npar,1,npar);
                   4190:   free_vector(x,1,npar);
                   4191:   free_ivector(indx,1,npar);
1.203     brouard  4192:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4193: 
                   4194: 
                   4195: }
                   4196: 
                   4197: /*************** hessian matrix ****************/
                   4198: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4199: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4200:   int i;
                   4201:   int l=1, lmax=20;
1.203     brouard  4202:   double k1,k2, res, fx;
1.132     brouard  4203:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4204:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4205:   int k=0,kmax=10;
                   4206:   double l1;
                   4207: 
                   4208:   fx=func(x);
                   4209:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4210:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4211:     l1=pow(10,l);
                   4212:     delts=delt;
                   4213:     for(k=1 ; k <kmax; k=k+1){
                   4214:       delt = delta*(l1*k);
                   4215:       p2[theta]=x[theta] +delt;
1.145     brouard  4216:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4217:       p2[theta]=x[theta]-delt;
                   4218:       k2=func(p2)-fx;
                   4219:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4220:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4221:       
1.203     brouard  4222: #ifdef DEBUGHESSII
1.126     brouard  4223:       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);
                   4224:       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);
                   4225: #endif
                   4226:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4227:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4228:        k=kmax;
                   4229:       }
                   4230:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4231:        k=kmax; l=lmax*10;
1.126     brouard  4232:       }
                   4233:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4234:        delts=delt;
                   4235:       }
1.203     brouard  4236:     } /* End loop k */
1.126     brouard  4237:   }
                   4238:   delti[theta]=delts;
                   4239:   return res; 
                   4240:   
                   4241: }
                   4242: 
1.203     brouard  4243: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4244: {
                   4245:   int i;
1.164     brouard  4246:   int l=1, lmax=20;
1.126     brouard  4247:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4248:   double p2[MAXPARM+1];
1.203     brouard  4249:   int k, kmax=1;
                   4250:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4251: 
                   4252:   int firstime=0;
1.203     brouard  4253:   
1.126     brouard  4254:   fx=func(x);
1.203     brouard  4255:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4256:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4257:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4258:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4259:     k1=func(p2)-fx;
                   4260:   
1.203     brouard  4261:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4262:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4263:     k2=func(p2)-fx;
                   4264:   
1.203     brouard  4265:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4266:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4267:     k3=func(p2)-fx;
                   4268:   
1.203     brouard  4269:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4270:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4271:     k4=func(p2)-fx;
1.203     brouard  4272:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4273:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4274:       firstime=1;
1.203     brouard  4275:       kmax=kmax+10;
1.208     brouard  4276:     }
                   4277:     if(kmax >=10 || firstime ==1){
1.246     brouard  4278:       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);
                   4279:       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  4280:       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);
                   4281:       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);
                   4282:     }
                   4283: #ifdef DEBUGHESSIJ
                   4284:     v1=hess[thetai][thetai];
                   4285:     v2=hess[thetaj][thetaj];
                   4286:     cv12=res;
                   4287:     /* Computing eigen value of Hessian matrix */
                   4288:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4289:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4290:     if ((lc2 <0) || (lc1 <0) ){
                   4291:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4292:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4293:       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);
                   4294:       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);
                   4295:     }
1.126     brouard  4296: #endif
                   4297:   }
                   4298:   return res;
                   4299: }
                   4300: 
1.203     brouard  4301:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4302: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4303: /* { */
                   4304: /*   int i; */
                   4305: /*   int l=1, lmax=20; */
                   4306: /*   double k1,k2,k3,k4,res,fx; */
                   4307: /*   double p2[MAXPARM+1]; */
                   4308: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4309: /*   int k=0,kmax=10; */
                   4310: /*   double l1; */
                   4311:   
                   4312: /*   fx=func(x); */
                   4313: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4314: /*     l1=pow(10,l); */
                   4315: /*     delts=delt; */
                   4316: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4317: /*       delt = delti*(l1*k); */
                   4318: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4319: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4320: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4321: /*       k1=func(p2)-fx; */
                   4322:       
                   4323: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4324: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4325: /*       k2=func(p2)-fx; */
                   4326:       
                   4327: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4328: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4329: /*       k3=func(p2)-fx; */
                   4330:       
                   4331: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4332: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4333: /*       k4=func(p2)-fx; */
                   4334: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4335: /* #ifdef DEBUGHESSIJ */
                   4336: /*       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4); */
                   4337: /*       fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4); */
                   4338: /* #endif */
                   4339: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4340: /*     k=kmax; */
                   4341: /*       } */
                   4342: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4343: /*     k=kmax; l=lmax*10; */
                   4344: /*       } */
                   4345: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4346: /*     delts=delt; */
                   4347: /*       } */
                   4348: /*     } /\* End loop k *\/ */
                   4349: /*   } */
                   4350: /*   delti[theta]=delts; */
                   4351: /*   return res;  */
                   4352: /* } */
                   4353: 
                   4354: 
1.126     brouard  4355: /************** Inverse of matrix **************/
                   4356: void ludcmp(double **a, int n, int *indx, double *d) 
                   4357: { 
                   4358:   int i,imax,j,k; 
                   4359:   double big,dum,sum,temp; 
                   4360:   double *vv; 
                   4361:  
                   4362:   vv=vector(1,n); 
                   4363:   *d=1.0; 
                   4364:   for (i=1;i<=n;i++) { 
                   4365:     big=0.0; 
                   4366:     for (j=1;j<=n;j++) 
                   4367:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4368:     if (big == 0.0){
                   4369:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4370:       for (j=1;j<=n;j++) {
                   4371:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4372:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4373:       }
                   4374:       fflush(ficlog);
                   4375:       fclose(ficlog);
                   4376:       nrerror("Singular matrix in routine ludcmp"); 
                   4377:     }
1.126     brouard  4378:     vv[i]=1.0/big; 
                   4379:   } 
                   4380:   for (j=1;j<=n;j++) { 
                   4381:     for (i=1;i<j;i++) { 
                   4382:       sum=a[i][j]; 
                   4383:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4384:       a[i][j]=sum; 
                   4385:     } 
                   4386:     big=0.0; 
                   4387:     for (i=j;i<=n;i++) { 
                   4388:       sum=a[i][j]; 
                   4389:       for (k=1;k<j;k++) 
                   4390:        sum -= a[i][k]*a[k][j]; 
                   4391:       a[i][j]=sum; 
                   4392:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4393:        big=dum; 
                   4394:        imax=i; 
                   4395:       } 
                   4396:     } 
                   4397:     if (j != imax) { 
                   4398:       for (k=1;k<=n;k++) { 
                   4399:        dum=a[imax][k]; 
                   4400:        a[imax][k]=a[j][k]; 
                   4401:        a[j][k]=dum; 
                   4402:       } 
                   4403:       *d = -(*d); 
                   4404:       vv[imax]=vv[j]; 
                   4405:     } 
                   4406:     indx[j]=imax; 
                   4407:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4408:     if (j != n) { 
                   4409:       dum=1.0/(a[j][j]); 
                   4410:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4411:     } 
                   4412:   } 
                   4413:   free_vector(vv,1,n);  /* Doesn't work */
                   4414: ;
                   4415: } 
                   4416: 
                   4417: void lubksb(double **a, int n, int *indx, double b[]) 
                   4418: { 
                   4419:   int i,ii=0,ip,j; 
                   4420:   double sum; 
                   4421:  
                   4422:   for (i=1;i<=n;i++) { 
                   4423:     ip=indx[i]; 
                   4424:     sum=b[ip]; 
                   4425:     b[ip]=b[i]; 
                   4426:     if (ii) 
                   4427:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4428:     else if (sum) ii=i; 
                   4429:     b[i]=sum; 
                   4430:   } 
                   4431:   for (i=n;i>=1;i--) { 
                   4432:     sum=b[i]; 
                   4433:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4434:     b[i]=sum/a[i][i]; 
                   4435:   } 
                   4436: } 
                   4437: 
                   4438: void pstamp(FILE *fichier)
                   4439: {
1.196     brouard  4440:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4441: }
                   4442: 
1.297     brouard  4443: void date2dmy(double date,double *day, double *month, double *year){
                   4444:   double yp=0., yp1=0., yp2=0.;
                   4445:   
                   4446:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4447:                        fractional in yp1 */
                   4448:   *year=yp;
                   4449:   yp2=modf((yp1*12),&yp);
                   4450:   *month=yp;
                   4451:   yp1=modf((yp2*30.5),&yp);
                   4452:   *day=yp;
                   4453:   if(*day==0) *day=1;
                   4454:   if(*month==0) *month=1;
                   4455: }
                   4456: 
1.253     brouard  4457: 
                   4458: 
1.126     brouard  4459: /************ Frequencies ********************/
1.251     brouard  4460: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4461:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4462:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4463: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4464:   
1.265     brouard  4465:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4466:   int iind=0, iage=0;
                   4467:   int mi; /* Effective wave */
                   4468:   int first;
                   4469:   double ***freq; /* Frequencies */
1.268     brouard  4470:   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 */
                   4471:   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  4472:   double *meanq, *stdq, *idq;
1.226     brouard  4473:   double **meanqt;
                   4474:   double *pp, **prop, *posprop, *pospropt;
                   4475:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4476:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4477:   double agebegin, ageend;
                   4478:     
                   4479:   pp=vector(1,nlstate);
1.251     brouard  4480:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4481:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4482:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4483:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4484:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4485:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4486:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4487:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4488:   strcpy(fileresp,"P_");
                   4489:   strcat(fileresp,fileresu);
                   4490:   /*strcat(fileresphtm,fileresu);*/
                   4491:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4492:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4493:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4494:     exit(0);
                   4495:   }
1.240     brouard  4496:   
1.226     brouard  4497:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4498:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4499:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4500:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4501:     fflush(ficlog);
                   4502:     exit(70); 
                   4503:   }
                   4504:   else{
                   4505:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4506: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4507: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4508:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4509:   }
1.237     brouard  4510:   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  4511:   
1.226     brouard  4512:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4513:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4514:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4515:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4516:     fflush(ficlog);
                   4517:     exit(70); 
1.240     brouard  4518:   } else{
1.226     brouard  4519:     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  4520: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4521: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4522:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4523:   }
1.240     brouard  4524:   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);
                   4525:   
1.253     brouard  4526:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4527:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4528:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4529:   j1=0;
1.126     brouard  4530:   
1.227     brouard  4531:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4532:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4533:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4534:   
                   4535:   
1.226     brouard  4536:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4537:      reference=low_education V1=0,V2=0
                   4538:      med_educ                V1=1 V2=0, 
                   4539:      high_educ               V1=0 V2=1
                   4540:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4541:   */
1.249     brouard  4542:   dateintsum=0;
                   4543:   k2cpt=0;
                   4544: 
1.253     brouard  4545:   if(cptcoveff == 0 )
1.265     brouard  4546:     nl=1;  /* Constant and age model only */
1.253     brouard  4547:   else
                   4548:     nl=2;
1.265     brouard  4549: 
                   4550:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4551:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4552:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4553:    *     freq[s1][s2][iage] =0.
                   4554:    *     Loop on iind
                   4555:    *       ++freq[s1][s2][iage] weighted
                   4556:    *     end iind
                   4557:    *     if covariate and j!0
                   4558:    *       headers Variable on one line
                   4559:    *     endif cov j!=0
                   4560:    *     header of frequency table by age
                   4561:    *     Loop on age
                   4562:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4563:    *       pos+=freq[s1][s2][iage] weighted
                   4564:    *       Loop on s1 initial state
                   4565:    *         fprintf(ficresp
                   4566:    *       end s1
                   4567:    *     end age
                   4568:    *     if j!=0 computes starting values
                   4569:    *     end compute starting values
                   4570:    *   end j1
                   4571:    * end nl 
                   4572:    */
1.253     brouard  4573:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4574:     if(nj==1)
                   4575:       j=0;  /* First pass for the constant */
1.265     brouard  4576:     else{
1.253     brouard  4577:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4578:     }
1.251     brouard  4579:     first=1;
1.265     brouard  4580:     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  4581:       posproptt=0.;
                   4582:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4583:        scanf("%d", i);*/
                   4584:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4585:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4586:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4587:            freq[i][s2][m]=0;
1.251     brouard  4588:       
                   4589:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4590:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4591:          prop[i][m]=0;
                   4592:        posprop[i]=0;
                   4593:        pospropt[i]=0;
                   4594:       }
1.283     brouard  4595:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4596:         idq[z1]=0.;
                   4597:         meanq[z1]=0.;
                   4598:         stdq[z1]=0.;
1.283     brouard  4599:       }
                   4600:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4601:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4602:       /*         meanqt[m][z1]=0.; */
                   4603:       /*       } */
                   4604:       /* }       */
1.251     brouard  4605:       /* dateintsum=0; */
                   4606:       /* k2cpt=0; */
                   4607:       
1.265     brouard  4608:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4609:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4610:        bool=1;
                   4611:        if(j !=0){
                   4612:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4613:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4614:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4615:                /* if(Tvaraff[z1] ==-20){ */
                   4616:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4617:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4618:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4619:                /* }else  */
                   4620:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4621:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4622:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4623:                  /* 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", 
                   4624:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4625:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4626:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4627:                } /* Onlyf fixed */
                   4628:              } /* end z1 */
                   4629:            } /* cptcovn > 0 */
                   4630:          } /* end any */
                   4631:        }/* end j==0 */
1.265     brouard  4632:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4633:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4634:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4635:            m=mw[mi][iind];
                   4636:            if(j!=0){
                   4637:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4638:                for (z1=1; z1<=cptcoveff; z1++) {
                   4639:                  if( Fixed[Tmodelind[z1]]==1){
                   4640:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4641:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4642:                                                                                      value is -1, we don't select. It differs from the 
                   4643:                                                                                      constant and age model which counts them. */
                   4644:                      bool=0; /* not selected */
                   4645:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4646:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4647:                      bool=0;
                   4648:                    }
                   4649:                  }
                   4650:                }
                   4651:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4652:            } /* end j==0 */
                   4653:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4654:            if(bool==1){ /*Selected */
1.251     brouard  4655:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4656:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4657:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4658:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4659:              if(m >=firstpass && m <=lastpass){
                   4660:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4661:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4662:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4663:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4664:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4665:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4666:                if (m<lastpass) {
                   4667:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4668:                  /*   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]); */
                   4669:                  if(s[m][iind]==-1)
                   4670:                    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.));
                   4671:                  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.284     brouard  4672:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean */
                   4673:                    idq[z1]=idq[z1]+weight[iind];
                   4674:                    meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4675:                    stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4676:                  }
1.251     brouard  4677:                  /* if((int)agev[m][iind] == 55) */
                   4678:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4679:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4680:                  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  4681:                }
1.251     brouard  4682:              } /* end if between passes */  
                   4683:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4684:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4685:                k2cpt++;
                   4686:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4687:              }
1.251     brouard  4688:            }else{
                   4689:              bool=1;
                   4690:            }/* end bool 2 */
                   4691:          } /* end m */
1.284     brouard  4692:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4693:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4694:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4695:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4696:          /* } */
1.251     brouard  4697:        } /* end bool */
                   4698:       } /* end iind = 1 to imx */
                   4699:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4700:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4701:       
                   4702:       
                   4703:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4704:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4705:         pstamp(ficresp);
1.251     brouard  4706:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4707:         pstamp(ficresp);
1.251     brouard  4708:        printf( "\n#********** Variable "); 
                   4709:        fprintf(ficresp, "\n#********** Variable "); 
                   4710:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4711:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4712:        fprintf(ficlog, "\n#********** Variable "); 
                   4713:        for (z1=1; z1<=cptcoveff; z1++){
                   4714:          if(!FixedV[Tvaraff[z1]]){
                   4715:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4716:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4717:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4718:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4719:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4720:          }else{
1.251     brouard  4721:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4722:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4723:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4724:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4725:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4726:          }
                   4727:        }
                   4728:        printf( "**********\n#");
                   4729:        fprintf(ficresp, "**********\n#");
                   4730:        fprintf(ficresphtm, "**********</h3>\n");
                   4731:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4732:        fprintf(ficlog, "**********\n");
                   4733:       }
1.284     brouard  4734:       /*
                   4735:        Printing means of quantitative variables if any
                   4736:       */
                   4737:       for (z1=1; z1<= nqfveff; z1++) {
1.285     brouard  4738:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.0f individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.284     brouard  4739:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   4740:        if(weightopt==1){
                   4741:          printf(" Weighted mean and standard deviation of");
                   4742:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4743:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4744:        }
1.285     brouard  4745:        printf(" fixed quantitative variable V%d on %.0f representatives of the population : %6.3g (%6.3g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt((stdq[z1]-meanq[z1]*meanq[z1]/idq[z1])/idq[z1]));
                   4746:        fprintf(ficlog," fixed quantitative variable V%d on %.0f representatives of the population : %6.3g (%6.3g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt((stdq[z1]-meanq[z1]*meanq[z1]/idq[z1])/idq[z1]));
                   4747:        fprintf(ficresphtmfr," fixed quantitative variable V%d on %.0f representatives of the population : %6.3g (%6.3g)<p>\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt((stdq[z1]-meanq[z1]*meanq[z1]/idq[z1])/idq[z1]));
1.284     brouard  4748:       }
                   4749:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4750:       /*       for(m=1;m<=lastpass;m++){ */
                   4751:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4752:       /*   } */
                   4753:       /* } */
1.283     brouard  4754: 
1.251     brouard  4755:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4756:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4757:         fprintf(ficresp, " Age");
                   4758:       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  4759:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4760:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4761:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4762:       }
1.265     brouard  4763:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4764:       fprintf(ficresphtm, "\n");
                   4765:       
                   4766:       /* Header of frequency table by age */
                   4767:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4768:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4769:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4770:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4771:          if(s2!=0 && m!=0)
                   4772:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4773:        }
1.226     brouard  4774:       }
1.251     brouard  4775:       fprintf(ficresphtmfr, "\n");
                   4776:     
                   4777:       /* For each age */
                   4778:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4779:        fprintf(ficresphtm,"<tr>");
                   4780:        if(iage==iagemax+1){
                   4781:          fprintf(ficlog,"1");
                   4782:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4783:        }else if(iage==iagemax+2){
                   4784:          fprintf(ficlog,"0");
                   4785:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4786:        }else if(iage==iagemax+3){
                   4787:          fprintf(ficlog,"Total");
                   4788:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4789:        }else{
1.240     brouard  4790:          if(first==1){
1.251     brouard  4791:            first=0;
                   4792:            printf("See log file for details...\n");
                   4793:          }
                   4794:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4795:          fprintf(ficlog,"Age %d", iage);
                   4796:        }
1.265     brouard  4797:        for(s1=1; s1 <=nlstate ; s1++){
                   4798:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4799:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4800:        }
1.265     brouard  4801:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4802:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4803:            pos += freq[s1][m][iage];
                   4804:          if(pp[s1]>=1.e-10){
1.251     brouard  4805:            if(first==1){
1.265     brouard  4806:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4807:            }
1.265     brouard  4808:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4809:          }else{
                   4810:            if(first==1)
1.265     brouard  4811:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4812:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4813:          }
                   4814:        }
                   4815:       
1.265     brouard  4816:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4817:          /* posprop[s1]=0; */
                   4818:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4819:            pp[s1] += freq[s1][m][iage];
                   4820:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4821:       
                   4822:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4823:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4824:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4825:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4826:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4827:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4828:        }
                   4829:        
                   4830:        /* Writing ficresp */
                   4831:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4832:           if( iage <= iagemax){
                   4833:            fprintf(ficresp," %d",iage);
                   4834:           }
                   4835:         }else if( nj==2){
                   4836:           if( iage <= iagemax){
                   4837:            fprintf(ficresp," %d",iage);
                   4838:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4839:           }
1.240     brouard  4840:        }
1.265     brouard  4841:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4842:          if(pos>=1.e-5){
1.251     brouard  4843:            if(first==1)
1.265     brouard  4844:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4845:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4846:          }else{
                   4847:            if(first==1)
1.265     brouard  4848:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4849:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4850:          }
                   4851:          if( iage <= iagemax){
                   4852:            if(pos>=1.e-5){
1.265     brouard  4853:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4854:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4855:               }else if( nj==2){
                   4856:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4857:               }
                   4858:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4859:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4860:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4861:            } else{
                   4862:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4863:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4864:            }
1.240     brouard  4865:          }
1.265     brouard  4866:          pospropt[s1] +=posprop[s1];
                   4867:        } /* end loop s1 */
1.251     brouard  4868:        /* pospropt=0.; */
1.265     brouard  4869:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4870:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4871:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4872:              if(first==1){
1.265     brouard  4873:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4874:              }
1.265     brouard  4875:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4876:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4877:            }
1.265     brouard  4878:            if(s1!=0 && m!=0)
                   4879:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4880:          }
1.265     brouard  4881:        } /* end loop s1 */
1.251     brouard  4882:        posproptt=0.; 
1.265     brouard  4883:        for(s1=1; s1 <=nlstate; s1++){
                   4884:          posproptt += pospropt[s1];
1.251     brouard  4885:        }
                   4886:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4887:        fprintf(ficresphtm,"</tr>\n");
                   4888:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4889:          if(iage <= iagemax)
                   4890:            fprintf(ficresp,"\n");
1.240     brouard  4891:        }
1.251     brouard  4892:        if(first==1)
                   4893:          printf("Others in log...\n");
                   4894:        fprintf(ficlog,"\n");
                   4895:       } /* end loop age iage */
1.265     brouard  4896:       
1.251     brouard  4897:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4898:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4899:        if(posproptt < 1.e-5){
1.265     brouard  4900:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4901:        }else{
1.265     brouard  4902:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4903:        }
1.226     brouard  4904:       }
1.251     brouard  4905:       fprintf(ficresphtm,"</tr>\n");
                   4906:       fprintf(ficresphtm,"</table>\n");
                   4907:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4908:       if(posproptt < 1.e-5){
1.251     brouard  4909:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4910:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4911:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4912:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4913:        invalidvarcomb[j1]=1;
1.226     brouard  4914:       }else{
1.251     brouard  4915:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4916:        invalidvarcomb[j1]=0;
1.226     brouard  4917:       }
1.251     brouard  4918:       fprintf(ficresphtmfr,"</table>\n");
                   4919:       fprintf(ficlog,"\n");
                   4920:       if(j!=0){
                   4921:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4922:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4923:          for(k=1; k <=(nlstate+ndeath); k++){
                   4924:            if (k != i) {
1.265     brouard  4925:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4926:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4927:                  if(j1==1){ /* All dummy covariates to zero */
                   4928:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4929:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4930:                    printf("%d%d ",i,k);
                   4931:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4932:                    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]));
                   4933:                    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]));
                   4934:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4935:                  }
1.253     brouard  4936:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4937:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4938:                    x[iage]= (double)iage;
                   4939:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  4940:                    /* 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  4941:                  }
1.268     brouard  4942:                  /* Some are not finite, but linreg will ignore these ages */
                   4943:                  no=0;
1.253     brouard  4944:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  4945:                  pstart[s1]=b;
                   4946:                  pstart[s1-1]=a;
1.252     brouard  4947:                }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 */ 
                   4948:                  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]);
                   4949:                  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  4950:                  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  4951:                  printf("%d%d ",i,k);
                   4952:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4953:                  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  4954:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4955:                  ;
                   4956:                }
                   4957:                /* printf("%12.7f )", param[i][jj][k]); */
                   4958:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4959:                s1++; 
1.251     brouard  4960:              } /* end jj */
                   4961:            } /* end k!= i */
                   4962:          } /* end k */
1.265     brouard  4963:        } /* end i, s1 */
1.251     brouard  4964:       } /* end j !=0 */
                   4965:     } /* end selected combination of covariate j1 */
                   4966:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4967:       printf("#Freqsummary: Starting values for the constants:\n");
                   4968:       fprintf(ficlog,"\n");
1.265     brouard  4969:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4970:        for(k=1; k <=(nlstate+ndeath); k++){
                   4971:          if (k != i) {
                   4972:            printf("%d%d ",i,k);
                   4973:            fprintf(ficlog,"%d%d ",i,k);
                   4974:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  4975:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  4976:              if(jj==1){ /* Age has to be done */
1.265     brouard  4977:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   4978:                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]));
                   4979:                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  4980:              }
                   4981:              /* printf("%12.7f )", param[i][jj][k]); */
                   4982:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4983:              s1++; 
1.250     brouard  4984:            }
1.251     brouard  4985:            printf("\n");
                   4986:            fprintf(ficlog,"\n");
1.250     brouard  4987:          }
                   4988:        }
1.284     brouard  4989:       } /* end of state i */
1.251     brouard  4990:       printf("#Freqsummary\n");
                   4991:       fprintf(ficlog,"\n");
1.265     brouard  4992:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   4993:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   4994:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   4995:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4996:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4997:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   4998:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   4999:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5000:          /* } */
                   5001:        }
1.265     brouard  5002:       } /* end loop s1 */
1.251     brouard  5003:       
                   5004:       printf("\n");
                   5005:       fprintf(ficlog,"\n");
                   5006:     } /* end j=0 */
1.249     brouard  5007:   } /* end j */
1.252     brouard  5008: 
1.253     brouard  5009:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5010:     for(i=1, jk=1; i <=nlstate; i++){
                   5011:       for(j=1; j <=nlstate+ndeath; j++){
                   5012:        if(j!=i){
                   5013:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5014:          printf("%1d%1d",i,j);
                   5015:          fprintf(ficparo,"%1d%1d",i,j);
                   5016:          for(k=1; k<=ncovmodel;k++){
                   5017:            /*    printf(" %lf",param[i][j][k]); */
                   5018:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5019:            p[jk]=pstart[jk];
                   5020:            printf(" %f ",pstart[jk]);
                   5021:            fprintf(ficparo," %f ",pstart[jk]);
                   5022:            jk++;
                   5023:          }
                   5024:          printf("\n");
                   5025:          fprintf(ficparo,"\n");
                   5026:        }
                   5027:       }
                   5028:     }
                   5029:   } /* end mle=-2 */
1.226     brouard  5030:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5031:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5032:   
1.226     brouard  5033:   fclose(ficresp);
                   5034:   fclose(ficresphtm);
                   5035:   fclose(ficresphtmfr);
1.283     brouard  5036:   free_vector(idq,1,nqfveff);
1.226     brouard  5037:   free_vector(meanq,1,nqfveff);
1.284     brouard  5038:   free_vector(stdq,1,nqfveff);
1.226     brouard  5039:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5040:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5041:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5042:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5043:   free_vector(pospropt,1,nlstate);
                   5044:   free_vector(posprop,1,nlstate);
1.251     brouard  5045:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5046:   free_vector(pp,1,nlstate);
                   5047:   /* End of freqsummary */
                   5048: }
1.126     brouard  5049: 
1.268     brouard  5050: /* Simple linear regression */
                   5051: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5052: 
                   5053:   /* y=a+bx regression */
                   5054:   double   sumx = 0.0;                        /* sum of x                      */
                   5055:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5056:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5057:   double   sumy = 0.0;                        /* sum of y                      */
                   5058:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5059:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5060:   double yhat;
                   5061:   
                   5062:   double denom=0;
                   5063:   int i;
                   5064:   int ne=*no;
                   5065:   
                   5066:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5067:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5068:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5069:       continue;
                   5070:     }
                   5071:     ne=ne+1;
                   5072:     sumx  += x[i];       
                   5073:     sumx2 += x[i]*x[i];  
                   5074:     sumxy += x[i] * y[i];
                   5075:     sumy  += y[i];      
                   5076:     sumy2 += y[i]*y[i]; 
                   5077:     denom = (ne * sumx2 - sumx*sumx);
                   5078:     /* 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); */
                   5079:   } 
                   5080:   
                   5081:   denom = (ne * sumx2 - sumx*sumx);
                   5082:   if (denom == 0) {
                   5083:     // vertical, slope m is infinity
                   5084:     *b = INFINITY;
                   5085:     *a = 0;
                   5086:     if (r) *r = 0;
                   5087:     return 1;
                   5088:   }
                   5089:   
                   5090:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5091:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5092:   if (r!=NULL) {
                   5093:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5094:       sqrt((sumx2 - sumx*sumx/ne) *
                   5095:           (sumy2 - sumy*sumy/ne));
                   5096:   }
                   5097:   *no=ne;
                   5098:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5099:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5100:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5101:       continue;
                   5102:     }
                   5103:     ne=ne+1;
                   5104:     yhat = y[i] - *a -*b* x[i];
                   5105:     sume2  += yhat * yhat ;       
                   5106:     
                   5107:     denom = (ne * sumx2 - sumx*sumx);
                   5108:     /* 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); */
                   5109:   } 
                   5110:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5111:   *sa= *sb * sqrt(sumx2/ne);
                   5112:   
                   5113:   return 0; 
                   5114: }
                   5115: 
1.126     brouard  5116: /************ Prevalence ********************/
1.227     brouard  5117: 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)
                   5118: {  
                   5119:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5120:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5121:      We still use firstpass and lastpass as another selection.
                   5122:   */
1.126     brouard  5123:  
1.227     brouard  5124:   int i, m, jk, j1, bool, z1,j, iv;
                   5125:   int mi; /* Effective wave */
                   5126:   int iage;
                   5127:   double agebegin, ageend;
                   5128: 
                   5129:   double **prop;
                   5130:   double posprop; 
                   5131:   double  y2; /* in fractional years */
                   5132:   int iagemin, iagemax;
                   5133:   int first; /** to stop verbosity which is redirected to log file */
                   5134: 
                   5135:   iagemin= (int) agemin;
                   5136:   iagemax= (int) agemax;
                   5137:   /*pp=vector(1,nlstate);*/
1.251     brouard  5138:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5139:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5140:   j1=0;
1.222     brouard  5141:   
1.227     brouard  5142:   /*j=cptcoveff;*/
                   5143:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5144:   
1.288     brouard  5145:   first=0;
1.227     brouard  5146:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5147:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5148:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5149:        prop[i][iage]=0.0;
                   5150:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5151:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5152:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5153:     
                   5154:     for (i=1; i<=imx; i++) { /* Each individual */
                   5155:       bool=1;
                   5156:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5157:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5158:        m=mw[mi][i];
                   5159:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5160:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5161:        for (z1=1; z1<=cptcoveff; z1++){
                   5162:          if( Fixed[Tmodelind[z1]]==1){
                   5163:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5164:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5165:              bool=0;
                   5166:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5167:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5168:              bool=0;
                   5169:            }
                   5170:        }
                   5171:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5172:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5173:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5174:          if(m >=firstpass && m <=lastpass){
                   5175:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5176:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5177:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5178:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5179:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5180:                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); 
                   5181:                exit(1);
                   5182:              }
                   5183:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5184:                /*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]]);*/
                   5185:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5186:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5187:              } /* end valid statuses */ 
                   5188:            } /* end selection of dates */
                   5189:          } /* end selection of waves */
                   5190:        } /* end bool */
                   5191:       } /* end wave */
                   5192:     } /* end individual */
                   5193:     for(i=iagemin; i <= iagemax+3; i++){  
                   5194:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5195:        posprop += prop[jk][i]; 
                   5196:       } 
                   5197:       
                   5198:       for(jk=1; jk <=nlstate ; jk++){      
                   5199:        if( i <=  iagemax){ 
                   5200:          if(posprop>=1.e-5){ 
                   5201:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5202:          } else{
1.288     brouard  5203:            if(!first){
                   5204:              first=1;
1.266     brouard  5205:              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]);
                   5206:            }else{
1.288     brouard  5207:              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  5208:            }
                   5209:          }
                   5210:        } 
                   5211:       }/* end jk */ 
                   5212:     }/* end i */ 
1.222     brouard  5213:      /*} *//* end i1 */
1.227     brouard  5214:   } /* end j1 */
1.222     brouard  5215:   
1.227     brouard  5216:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5217:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5218:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5219: }  /* End of prevalence */
1.126     brouard  5220: 
                   5221: /************* Waves Concatenation ***************/
                   5222: 
                   5223: 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)
                   5224: {
1.298     brouard  5225:   /* 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  5226:      Death is a valid wave (if date is known).
                   5227:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5228:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5229:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5230:   */
1.126     brouard  5231: 
1.224     brouard  5232:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5233:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5234:      double sum=0., jmean=0.;*/
1.224     brouard  5235:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5236:   int j, k=0,jk, ju, jl;
                   5237:   double sum=0.;
                   5238:   first=0;
1.214     brouard  5239:   firstwo=0;
1.217     brouard  5240:   firsthree=0;
1.218     brouard  5241:   firstfour=0;
1.164     brouard  5242:   jmin=100000;
1.126     brouard  5243:   jmax=-1;
                   5244:   jmean=0.;
1.224     brouard  5245: 
                   5246: /* Treating live states */
1.214     brouard  5247:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5248:     mi=0;  /* First valid wave */
1.227     brouard  5249:     mli=0; /* Last valid wave */
1.126     brouard  5250:     m=firstpass;
1.214     brouard  5251:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  5252:       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 */
                   5253:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5254:       }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 */
                   5255:        mw[++mi][i]=m;
                   5256:        mli=m;
1.224     brouard  5257:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5258:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5259:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5260:       }
1.227     brouard  5261:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  5262: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5263:        break;
1.224     brouard  5264: #else
1.227     brouard  5265:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   5266:          if(firsthree == 0){
1.302     brouard  5267:            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  5268:            firsthree=1;
                   5269:          }
1.302     brouard  5270:          fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as 1-p_{%d%d} .\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m, s[m][i], nlstate+ndeath);
1.227     brouard  5271:          mw[++mi][i]=m;
                   5272:          mli=m;
                   5273:        }
                   5274:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5275:          nbwarn++;
                   5276:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   5277:            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);
                   5278:            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);
                   5279:          }
                   5280:          break;
                   5281:        }
                   5282:        break;
1.224     brouard  5283: #endif
1.227     brouard  5284:       }/* End m >= lastpass */
1.126     brouard  5285:     }/* end while */
1.224     brouard  5286: 
1.227     brouard  5287:     /* 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  5288:     /* After last pass */
1.224     brouard  5289: /* Treating death states */
1.214     brouard  5290:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5291:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5292:       /* } */
1.126     brouard  5293:       mi++;    /* Death is another wave */
                   5294:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5295:       /* Only death is a correct wave */
1.126     brouard  5296:       mw[mi][i]=m;
1.257     brouard  5297:     } /* else not in a death state */
1.224     brouard  5298: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5299:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5300:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  5301:        if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* death occured before last wave and status should have been death instead of -1 */
                   5302:          nbwarn++;
                   5303:          if(firstfiv==0){
                   5304:            printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %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 );
                   5305:            firstfiv=1;
                   5306:          }else{
                   5307:            fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %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 );
                   5308:          }
                   5309:        }else{ /* Death occured afer last wave potential bias */
                   5310:          nberr++;
                   5311:          if(firstwo==0){
1.257     brouard  5312:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%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. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). 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], i,m );
1.227     brouard  5313:            firstwo=1;
                   5314:          }
1.257     brouard  5315:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%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. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.227     brouard  5316:        }
1.257     brouard  5317:       }else{ /* if date of interview is unknown */
1.227     brouard  5318:        /* death is known but not confirmed by death status at any wave */
                   5319:        if(firstfour==0){
                   5320:          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. 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], i,m );
                   5321:          firstfour=1;
                   5322:        }
                   5323:        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. 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], i,m );
1.214     brouard  5324:       }
1.224     brouard  5325:     } /* end if date of death is known */
                   5326: #endif
                   5327:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   5328:     /* wav[i]=mw[mi][i]; */
1.126     brouard  5329:     if(mi==0){
                   5330:       nbwarn++;
                   5331:       if(first==0){
1.227     brouard  5332:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5333:        first=1;
1.126     brouard  5334:       }
                   5335:       if(first==1){
1.227     brouard  5336:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5337:       }
                   5338:     } /* end mi==0 */
                   5339:   } /* End individuals */
1.214     brouard  5340:   /* wav and mw are no more changed */
1.223     brouard  5341:        
1.214     brouard  5342:   
1.126     brouard  5343:   for(i=1; i<=imx; i++){
                   5344:     for(mi=1; mi<wav[i];mi++){
                   5345:       if (stepm <=0)
1.227     brouard  5346:        dh[mi][i]=1;
1.126     brouard  5347:       else{
1.260     brouard  5348:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5349:          if (agedc[i] < 2*AGESUP) {
                   5350:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5351:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5352:            else if(j<0){
                   5353:              nberr++;
                   5354:              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]);
                   5355:              j=1; /* Temporary Dangerous patch */
                   5356:              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);
                   5357:              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]);
                   5358:              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);
                   5359:            }
                   5360:            k=k+1;
                   5361:            if (j >= jmax){
                   5362:              jmax=j;
                   5363:              ijmax=i;
                   5364:            }
                   5365:            if (j <= jmin){
                   5366:              jmin=j;
                   5367:              ijmin=i;
                   5368:            }
                   5369:            sum=sum+j;
                   5370:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5371:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5372:          }
                   5373:        }
                   5374:        else{
                   5375:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5376: /*       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  5377:                                        
1.227     brouard  5378:          k=k+1;
                   5379:          if (j >= jmax) {
                   5380:            jmax=j;
                   5381:            ijmax=i;
                   5382:          }
                   5383:          else if (j <= jmin){
                   5384:            jmin=j;
                   5385:            ijmin=i;
                   5386:          }
                   5387:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5388:          /*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]);*/
                   5389:          if(j<0){
                   5390:            nberr++;
                   5391:            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]);
                   5392:            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]);
                   5393:          }
                   5394:          sum=sum+j;
                   5395:        }
                   5396:        jk= j/stepm;
                   5397:        jl= j -jk*stepm;
                   5398:        ju= j -(jk+1)*stepm;
                   5399:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5400:          if(jl==0){
                   5401:            dh[mi][i]=jk;
                   5402:            bh[mi][i]=0;
                   5403:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5404:                  * to avoid the price of an extra matrix product in likelihood */
                   5405:            dh[mi][i]=jk+1;
                   5406:            bh[mi][i]=ju;
                   5407:          }
                   5408:        }else{
                   5409:          if(jl <= -ju){
                   5410:            dh[mi][i]=jk;
                   5411:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5412:                                 * is higher than the multiple of stepm and negative otherwise.
                   5413:                                 */
                   5414:          }
                   5415:          else{
                   5416:            dh[mi][i]=jk+1;
                   5417:            bh[mi][i]=ju;
                   5418:          }
                   5419:          if(dh[mi][i]==0){
                   5420:            dh[mi][i]=1; /* At least one step */
                   5421:            bh[mi][i]=ju; /* At least one step */
                   5422:            /*  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);*/
                   5423:          }
                   5424:        } /* end if mle */
1.126     brouard  5425:       }
                   5426:     } /* end wave */
                   5427:   }
                   5428:   jmean=sum/k;
                   5429:   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  5430:   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  5431: }
1.126     brouard  5432: 
                   5433: /*********** Tricode ****************************/
1.220     brouard  5434:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5435:  {
                   5436:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5437:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5438:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5439:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5440:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5441:     */
1.130     brouard  5442: 
1.242     brouard  5443:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5444:    int modmaxcovj=0; /* Modality max of covariates j */
                   5445:    int cptcode=0; /* Modality max of covariates j */
                   5446:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5447: 
                   5448: 
1.242     brouard  5449:    /* cptcoveff=0;  */
                   5450:    /* *cptcov=0; */
1.126     brouard  5451:  
1.242     brouard  5452:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5453:    for (k=1; k <= maxncov; k++)
                   5454:      for(j=1; j<=2; j++)
                   5455:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5456: 
1.242     brouard  5457:    /* Loop on covariates without age and products and no quantitative variable */
                   5458:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5459:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5460:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5461:        switch(Fixed[k]) {
                   5462:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5463:         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*/
                   5464:           ij=(int)(covar[Tvar[k]][i]);
                   5465:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5466:            * If product of Vn*Vm, still boolean *:
                   5467:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5468:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5469:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5470:              modality of the nth covariate of individual i. */
                   5471:           if (ij > modmaxcovj)
                   5472:             modmaxcovj=ij; 
                   5473:           else if (ij < modmincovj) 
                   5474:             modmincovj=ij; 
1.287     brouard  5475:           if (ij <0 || ij >1 ){
                   5476:             printf("Information, IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5477:             fprintf(ficlog,"Information, currently IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5478:           }
                   5479:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5480:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5481:             exit(1);
                   5482:           }else
                   5483:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5484:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5485:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5486:           /* getting the maximum value of the modality of the covariate
                   5487:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5488:              female ies 1, then modmaxcovj=1.
                   5489:           */
                   5490:         } /* end for loop on individuals i */
                   5491:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5492:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5493:         cptcode=modmaxcovj;
                   5494:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5495:         /*for (i=0; i<=cptcode; i++) {*/
                   5496:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5497:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5498:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5499:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5500:             if( j != -1){
                   5501:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5502:                                  covariate for which somebody answered excluding 
                   5503:                                  undefined. Usually 2: 0 and 1. */
                   5504:             }
                   5505:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5506:                                     covariate for which somebody answered including 
                   5507:                                     undefined. Usually 3: -1, 0 and 1. */
                   5508:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5509:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5510:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5511:                        
1.242     brouard  5512:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5513:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5514:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5515:         /* modmincovj=3; modmaxcovj = 7; */
                   5516:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5517:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5518:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5519:         /* nbcode[Tvar[j]][ij]=k; */
                   5520:         /* nbcode[Tvar[j]][1]=0; */
                   5521:         /* nbcode[Tvar[j]][2]=1; */
                   5522:         /* nbcode[Tvar[j]][3]=2; */
                   5523:         /* To be continued (not working yet). */
                   5524:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5525: 
                   5526:         /* 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*/
                   5527:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5528:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5529:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5530:         /*, could be restored in the future */
                   5531:         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  5532:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5533:             break;
                   5534:           }
                   5535:           ij++;
1.287     brouard  5536:           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  5537:           cptcode = ij; /* New max modality for covar j */
                   5538:         } /* end of loop on modality i=-1 to 1 or more */
                   5539:         break;
                   5540:        case 1: /* Testing on varying covariate, could be simple and
                   5541:                * should look at waves or product of fixed *
                   5542:                * varying. No time to test -1, assuming 0 and 1 only */
                   5543:         ij=0;
                   5544:         for(i=0; i<=1;i++){
                   5545:           nbcode[Tvar[k]][++ij]=i;
                   5546:         }
                   5547:         break;
                   5548:        default:
                   5549:         break;
                   5550:        } /* end switch */
                   5551:      } /* end dummy test */
1.287     brouard  5552:    } /* 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  5553:   
                   5554:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5555:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5556:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5557:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5558:      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 */ 
                   5559:      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 */
                   5560:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5561:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5562:   
                   5563:    ij=0;
                   5564:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5565:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5566:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5567:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5568:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5569:        /* If product not in single variable we don't print results */
                   5570:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5571:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5572:        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*/
                   5573:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5574:        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 */
                   5575:        if(Fixed[k]!=0)
                   5576:         anyvaryingduminmodel=1;
                   5577:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5578:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5579:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5580:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5581:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5582:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5583:      } 
                   5584:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5585:    /* ij--; */
                   5586:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5587:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5588:                * because they can be excluded from the model and real
                   5589:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5590:    for(j=ij+1; j<= cptcovt; j++){
                   5591:      Tvaraff[j]=0;
                   5592:      Tmodelind[j]=0;
                   5593:    }
                   5594:    for(j=ntveff+1; j<= cptcovt; j++){
                   5595:      TmodelInvind[j]=0;
                   5596:    }
                   5597:    /* To be sorted */
                   5598:    ;
                   5599:  }
1.126     brouard  5600: 
1.145     brouard  5601: 
1.126     brouard  5602: /*********** Health Expectancies ****************/
                   5603: 
1.235     brouard  5604:  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  5605: 
                   5606: {
                   5607:   /* Health expectancies, no variances */
1.164     brouard  5608:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5609:   int nhstepma, nstepma; /* Decreasing with age */
                   5610:   double age, agelim, hf;
                   5611:   double ***p3mat;
                   5612:   double eip;
                   5613: 
1.238     brouard  5614:   /* pstamp(ficreseij); */
1.126     brouard  5615:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5616:   fprintf(ficreseij,"# Age");
                   5617:   for(i=1; i<=nlstate;i++){
                   5618:     for(j=1; j<=nlstate;j++){
                   5619:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5620:     }
                   5621:     fprintf(ficreseij," e%1d. ",i);
                   5622:   }
                   5623:   fprintf(ficreseij,"\n");
                   5624: 
                   5625:   
                   5626:   if(estepm < stepm){
                   5627:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5628:   }
                   5629:   else  hstepm=estepm;   
                   5630:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5631:    * This is mainly to measure the difference between two models: for example
                   5632:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5633:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5634:    * progression in between and thus overestimating or underestimating according
                   5635:    * to the curvature of the survival function. If, for the same date, we 
                   5636:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5637:    * to compare the new estimate of Life expectancy with the same linear 
                   5638:    * hypothesis. A more precise result, taking into account a more precise
                   5639:    * curvature will be obtained if estepm is as small as stepm. */
                   5640: 
                   5641:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5642:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5643:      nhstepm is the number of hstepm from age to agelim 
                   5644:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5645:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5646:      and note for a fixed period like estepm months */
                   5647:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5648:      survival function given by stepm (the optimization length). Unfortunately it
                   5649:      means that if the survival funtion is printed only each two years of age and if
                   5650:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5651:      results. So we changed our mind and took the option of the best precision.
                   5652:   */
                   5653:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5654: 
                   5655:   agelim=AGESUP;
                   5656:   /* If stepm=6 months */
                   5657:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5658:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5659:     
                   5660: /* nhstepm age range expressed in number of stepm */
                   5661:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5662:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5663:   /* if (stepm >= YEARM) hstepm=1;*/
                   5664:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5665:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5666: 
                   5667:   for (age=bage; age<=fage; age ++){ 
                   5668:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5669:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5670:     /* if (stepm >= YEARM) hstepm=1;*/
                   5671:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5672: 
                   5673:     /* If stepm=6 months */
                   5674:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5675:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5676:     
1.235     brouard  5677:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5678:     
                   5679:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5680:     
                   5681:     printf("%d|",(int)age);fflush(stdout);
                   5682:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5683:     
                   5684:     /* Computing expectancies */
                   5685:     for(i=1; i<=nlstate;i++)
                   5686:       for(j=1; j<=nlstate;j++)
                   5687:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5688:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5689:          
                   5690:          /* 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]);*/
                   5691: 
                   5692:        }
                   5693: 
                   5694:     fprintf(ficreseij,"%3.0f",age );
                   5695:     for(i=1; i<=nlstate;i++){
                   5696:       eip=0;
                   5697:       for(j=1; j<=nlstate;j++){
                   5698:        eip +=eij[i][j][(int)age];
                   5699:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5700:       }
                   5701:       fprintf(ficreseij,"%9.4f", eip );
                   5702:     }
                   5703:     fprintf(ficreseij,"\n");
                   5704:     
                   5705:   }
                   5706:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5707:   printf("\n");
                   5708:   fprintf(ficlog,"\n");
                   5709:   
                   5710: }
                   5711: 
1.235     brouard  5712:  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  5713: 
                   5714: {
                   5715:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5716:      to initial status i, ei. .
1.126     brouard  5717:   */
                   5718:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5719:   int nhstepma, nstepma; /* Decreasing with age */
                   5720:   double age, agelim, hf;
                   5721:   double ***p3matp, ***p3matm, ***varhe;
                   5722:   double **dnewm,**doldm;
                   5723:   double *xp, *xm;
                   5724:   double **gp, **gm;
                   5725:   double ***gradg, ***trgradg;
                   5726:   int theta;
                   5727: 
                   5728:   double eip, vip;
                   5729: 
                   5730:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5731:   xp=vector(1,npar);
                   5732:   xm=vector(1,npar);
                   5733:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5734:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5735:   
                   5736:   pstamp(ficresstdeij);
                   5737:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5738:   fprintf(ficresstdeij,"# Age");
                   5739:   for(i=1; i<=nlstate;i++){
                   5740:     for(j=1; j<=nlstate;j++)
                   5741:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5742:     fprintf(ficresstdeij," e%1d. ",i);
                   5743:   }
                   5744:   fprintf(ficresstdeij,"\n");
                   5745: 
                   5746:   pstamp(ficrescveij);
                   5747:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5748:   fprintf(ficrescveij,"# Age");
                   5749:   for(i=1; i<=nlstate;i++)
                   5750:     for(j=1; j<=nlstate;j++){
                   5751:       cptj= (j-1)*nlstate+i;
                   5752:       for(i2=1; i2<=nlstate;i2++)
                   5753:        for(j2=1; j2<=nlstate;j2++){
                   5754:          cptj2= (j2-1)*nlstate+i2;
                   5755:          if(cptj2 <= cptj)
                   5756:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5757:        }
                   5758:     }
                   5759:   fprintf(ficrescveij,"\n");
                   5760:   
                   5761:   if(estepm < stepm){
                   5762:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5763:   }
                   5764:   else  hstepm=estepm;   
                   5765:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5766:    * This is mainly to measure the difference between two models: for example
                   5767:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5768:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5769:    * progression in between and thus overestimating or underestimating according
                   5770:    * to the curvature of the survival function. If, for the same date, we 
                   5771:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5772:    * to compare the new estimate of Life expectancy with the same linear 
                   5773:    * hypothesis. A more precise result, taking into account a more precise
                   5774:    * curvature will be obtained if estepm is as small as stepm. */
                   5775: 
                   5776:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5777:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5778:      nhstepm is the number of hstepm from age to agelim 
                   5779:      nstepm is the number of stepm from age to agelin. 
                   5780:      Look at hpijx to understand the reason of that which relies in memory size
                   5781:      and note for a fixed period like estepm months */
                   5782:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5783:      survival function given by stepm (the optimization length). Unfortunately it
                   5784:      means that if the survival funtion is printed only each two years of age and if
                   5785:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5786:      results. So we changed our mind and took the option of the best precision.
                   5787:   */
                   5788:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5789: 
                   5790:   /* If stepm=6 months */
                   5791:   /* nhstepm age range expressed in number of stepm */
                   5792:   agelim=AGESUP;
                   5793:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5794:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5795:   /* if (stepm >= YEARM) hstepm=1;*/
                   5796:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5797:   
                   5798:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5799:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5800:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5801:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5802:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5803:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5804: 
                   5805:   for (age=bage; age<=fage; age ++){ 
                   5806:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5807:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5808:     /* if (stepm >= YEARM) hstepm=1;*/
                   5809:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5810:                
1.126     brouard  5811:     /* If stepm=6 months */
                   5812:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5813:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5814:     
                   5815:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5816:                
1.126     brouard  5817:     /* Computing  Variances of health expectancies */
                   5818:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5819:        decrease memory allocation */
                   5820:     for(theta=1; theta <=npar; theta++){
                   5821:       for(i=1; i<=npar; i++){ 
1.222     brouard  5822:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5823:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5824:       }
1.235     brouard  5825:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5826:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5827:                        
1.126     brouard  5828:       for(j=1; j<= nlstate; j++){
1.222     brouard  5829:        for(i=1; i<=nlstate; i++){
                   5830:          for(h=0; h<=nhstepm-1; h++){
                   5831:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5832:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5833:          }
                   5834:        }
1.126     brouard  5835:       }
1.218     brouard  5836:                        
1.126     brouard  5837:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5838:        for(h=0; h<=nhstepm-1; h++){
                   5839:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5840:        }
1.126     brouard  5841:     }/* End theta */
                   5842:     
                   5843:     
                   5844:     for(h=0; h<=nhstepm-1; h++)
                   5845:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5846:        for(theta=1; theta <=npar; theta++)
                   5847:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5848:     
1.218     brouard  5849:                
1.222     brouard  5850:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5851:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5852:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5853:                
1.222     brouard  5854:     printf("%d|",(int)age);fflush(stdout);
                   5855:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5856:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5857:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5858:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5859:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5860:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5861:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5862:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5863:       }
                   5864:     }
1.218     brouard  5865:                
1.126     brouard  5866:     /* Computing expectancies */
1.235     brouard  5867:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5868:     for(i=1; i<=nlstate;i++)
                   5869:       for(j=1; j<=nlstate;j++)
1.222     brouard  5870:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5871:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5872:                                        
1.222     brouard  5873:          /* 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  5874:                                        
1.222     brouard  5875:        }
1.269     brouard  5876: 
                   5877:     /* Standard deviation of expectancies ij */                
1.126     brouard  5878:     fprintf(ficresstdeij,"%3.0f",age );
                   5879:     for(i=1; i<=nlstate;i++){
                   5880:       eip=0.;
                   5881:       vip=0.;
                   5882:       for(j=1; j<=nlstate;j++){
1.222     brouard  5883:        eip += eij[i][j][(int)age];
                   5884:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5885:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5886:        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  5887:       }
                   5888:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5889:     }
                   5890:     fprintf(ficresstdeij,"\n");
1.218     brouard  5891:                
1.269     brouard  5892:     /* Variance of expectancies ij */          
1.126     brouard  5893:     fprintf(ficrescveij,"%3.0f",age );
                   5894:     for(i=1; i<=nlstate;i++)
                   5895:       for(j=1; j<=nlstate;j++){
1.222     brouard  5896:        cptj= (j-1)*nlstate+i;
                   5897:        for(i2=1; i2<=nlstate;i2++)
                   5898:          for(j2=1; j2<=nlstate;j2++){
                   5899:            cptj2= (j2-1)*nlstate+i2;
                   5900:            if(cptj2 <= cptj)
                   5901:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5902:          }
1.126     brouard  5903:       }
                   5904:     fprintf(ficrescveij,"\n");
1.218     brouard  5905:                
1.126     brouard  5906:   }
                   5907:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5908:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5909:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5910:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5911:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5912:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5913:   printf("\n");
                   5914:   fprintf(ficlog,"\n");
1.218     brouard  5915:        
1.126     brouard  5916:   free_vector(xm,1,npar);
                   5917:   free_vector(xp,1,npar);
                   5918:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5919:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5920:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5921: }
1.218     brouard  5922:  
1.126     brouard  5923: /************ Variance ******************/
1.235     brouard  5924:  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  5925:  {
1.279     brouard  5926:    /** Variance of health expectancies 
                   5927:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   5928:     * double **newm;
                   5929:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   5930:     */
1.218     brouard  5931:   
                   5932:    /* int movingaverage(); */
                   5933:    double **dnewm,**doldm;
                   5934:    double **dnewmp,**doldmp;
                   5935:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  5936:    int first=0;
1.218     brouard  5937:    int k;
                   5938:    double *xp;
1.279     brouard  5939:    double **gp, **gm;  /**< for var eij */
                   5940:    double ***gradg, ***trgradg; /**< for var eij */
                   5941:    double **gradgp, **trgradgp; /**< for var p point j */
                   5942:    double *gpp, *gmp; /**< for var p point j */
                   5943:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  5944:    double ***p3mat;
                   5945:    double age,agelim, hf;
                   5946:    /* double ***mobaverage; */
                   5947:    int theta;
                   5948:    char digit[4];
                   5949:    char digitp[25];
                   5950: 
                   5951:    char fileresprobmorprev[FILENAMELENGTH];
                   5952: 
                   5953:    if(popbased==1){
                   5954:      if(mobilav!=0)
                   5955:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5956:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5957:    }
                   5958:    else 
                   5959:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5960: 
1.218     brouard  5961:    /* if (mobilav!=0) { */
                   5962:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5963:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5964:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5965:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5966:    /*   } */
                   5967:    /* } */
                   5968: 
                   5969:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5970:    sprintf(digit,"%-d",ij);
                   5971:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5972:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5973:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5974:    strcat(fileresprobmorprev,fileresu);
                   5975:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5976:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5977:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5978:    }
                   5979:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5980:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5981:    pstamp(ficresprobmorprev);
                   5982:    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  5983:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5984:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5985:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5986:    }
                   5987:    for(j=1;j<=cptcoveff;j++) 
                   5988:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5989:    fprintf(ficresprobmorprev,"\n");
                   5990: 
1.218     brouard  5991:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5992:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5993:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5994:      for(i=1; i<=nlstate;i++)
                   5995:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5996:    }  
                   5997:    fprintf(ficresprobmorprev,"\n");
                   5998:   
                   5999:    fprintf(ficgp,"\n# Routine varevsij");
                   6000:    fprintf(ficgp,"\nunset title \n");
                   6001:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6002:    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");
                   6003:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6004: 
1.218     brouard  6005:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6006:    pstamp(ficresvij);
                   6007:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6008:    if(popbased==1)
                   6009:      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);
                   6010:    else
                   6011:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6012:    fprintf(ficresvij,"# Age");
                   6013:    for(i=1; i<=nlstate;i++)
                   6014:      for(j=1; j<=nlstate;j++)
                   6015:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6016:    fprintf(ficresvij,"\n");
                   6017: 
                   6018:    xp=vector(1,npar);
                   6019:    dnewm=matrix(1,nlstate,1,npar);
                   6020:    doldm=matrix(1,nlstate,1,nlstate);
                   6021:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6022:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6023: 
                   6024:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6025:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6026:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6027:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6028:   
1.218     brouard  6029:    if(estepm < stepm){
                   6030:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6031:    }
                   6032:    else  hstepm=estepm;   
                   6033:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6034:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6035:       nhstepm is the number of hstepm from age to agelim 
                   6036:       nstepm is the number of stepm from age to agelim. 
                   6037:       Look at function hpijx to understand why because of memory size limitations, 
                   6038:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6039:       survival function given by stepm (the optimization length). Unfortunately it
                   6040:       means that if the survival funtion is printed every two years of age and if
                   6041:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6042:       results. So we changed our mind and took the option of the best precision.
                   6043:    */
                   6044:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6045:    agelim = AGESUP;
                   6046:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6047:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6048:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6049:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6050:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6051:      gp=matrix(0,nhstepm,1,nlstate);
                   6052:      gm=matrix(0,nhstepm,1,nlstate);
                   6053:                
                   6054:                
                   6055:      for(theta=1; theta <=npar; theta++){
                   6056:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6057:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6058:        }
1.279     brouard  6059:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6060:        * returns into prlim .
1.288     brouard  6061:        */
1.242     brouard  6062:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6063: 
                   6064:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6065:        if (popbased==1) {
                   6066:         if(mobilav ==0){
                   6067:           for(i=1; i<=nlstate;i++)
                   6068:             prlim[i][i]=probs[(int)age][i][ij];
                   6069:         }else{ /* mobilav */ 
                   6070:           for(i=1; i<=nlstate;i++)
                   6071:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6072:         }
                   6073:        }
1.295     brouard  6074:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6075:        */                      
                   6076:        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  6077:        /**< 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  6078:        * at horizon h in state j including mortality.
                   6079:        */
1.218     brouard  6080:        for(j=1; j<= nlstate; j++){
                   6081:         for(h=0; h<=nhstepm; h++){
                   6082:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6083:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6084:         }
                   6085:        }
1.279     brouard  6086:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6087:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6088:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6089:        */
                   6090:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6091:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6092:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6093:        }
                   6094:        
                   6095:        /* Again with minus shift */
1.218     brouard  6096:                        
                   6097:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6098:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6099: 
1.242     brouard  6100:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6101:                        
                   6102:        if (popbased==1) {
                   6103:         if(mobilav ==0){
                   6104:           for(i=1; i<=nlstate;i++)
                   6105:             prlim[i][i]=probs[(int)age][i][ij];
                   6106:         }else{ /* mobilav */ 
                   6107:           for(i=1; i<=nlstate;i++)
                   6108:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6109:         }
                   6110:        }
                   6111:                        
1.235     brouard  6112:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6113:                        
                   6114:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6115:         for(h=0; h<=nhstepm; h++){
                   6116:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6117:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6118:         }
                   6119:        }
                   6120:        /* This for computing probability of death (h=1 means
                   6121:          computed over hstepm matrices product = hstepm*stepm months) 
                   6122:          as a weighted average of prlim.
                   6123:        */
                   6124:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6125:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6126:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6127:        }    
1.279     brouard  6128:        /* end shifting computations */
                   6129: 
                   6130:        /**< Computing gradient matrix at horizon h 
                   6131:        */
1.218     brouard  6132:        for(j=1; j<= nlstate; j++) /* vareij */
                   6133:         for(h=0; h<=nhstepm; h++){
                   6134:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6135:         }
1.279     brouard  6136:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6137:        */
                   6138:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6139:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6140:        }
                   6141:                        
                   6142:      } /* End theta */
1.279     brouard  6143:      
                   6144:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6145:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6146:                
                   6147:      for(h=0; h<=nhstepm; h++) /* veij */
                   6148:        for(j=1; j<=nlstate;j++)
                   6149:         for(theta=1; theta <=npar; theta++)
                   6150:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6151:                
                   6152:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6153:        for(theta=1; theta <=npar; theta++)
                   6154:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6155:      /**< as well as its transposed matrix 
                   6156:       */               
1.218     brouard  6157:                
                   6158:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6159:      for(i=1;i<=nlstate;i++)
                   6160:        for(j=1;j<=nlstate;j++)
                   6161:         vareij[i][j][(int)age] =0.;
1.279     brouard  6162: 
                   6163:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6164:       * and k (nhstepm) formula 15 of article
                   6165:       * Lievre-Brouard-Heathcote
                   6166:       */
                   6167:      
1.218     brouard  6168:      for(h=0;h<=nhstepm;h++){
                   6169:        for(k=0;k<=nhstepm;k++){
                   6170:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6171:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6172:         for(i=1;i<=nlstate;i++)
                   6173:           for(j=1;j<=nlstate;j++)
                   6174:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6175:        }
                   6176:      }
                   6177:                
1.279     brouard  6178:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6179:       * p.j overall mortality formula 49 but computed directly because
                   6180:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6181:       * wix is independent of theta.
                   6182:       */
1.218     brouard  6183:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6184:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6185:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6186:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6187:         varppt[j][i]=doldmp[j][i];
                   6188:      /* end ppptj */
                   6189:      /*  x centered again */
                   6190:                
1.242     brouard  6191:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6192:                
                   6193:      if (popbased==1) {
                   6194:        if(mobilav ==0){
                   6195:         for(i=1; i<=nlstate;i++)
                   6196:           prlim[i][i]=probs[(int)age][i][ij];
                   6197:        }else{ /* mobilav */ 
                   6198:         for(i=1; i<=nlstate;i++)
                   6199:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6200:        }
                   6201:      }
                   6202:                
                   6203:      /* This for computing probability of death (h=1 means
                   6204:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6205:        as a weighted average of prlim.
                   6206:      */
1.235     brouard  6207:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6208:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6209:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6210:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6211:      }    
                   6212:      /* end probability of death */
                   6213:                
                   6214:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6215:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6216:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6217:        for(i=1; i<=nlstate;i++){
                   6218:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6219:        }
                   6220:      } 
                   6221:      fprintf(ficresprobmorprev,"\n");
                   6222:                
                   6223:      fprintf(ficresvij,"%.0f ",age );
                   6224:      for(i=1; i<=nlstate;i++)
                   6225:        for(j=1; j<=nlstate;j++){
                   6226:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6227:        }
                   6228:      fprintf(ficresvij,"\n");
                   6229:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6230:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6231:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6232:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6233:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6234:    } /* End age */
                   6235:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6236:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6237:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6238:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6239:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6240:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6241:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6242:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6243:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6244:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6245:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6246:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6247:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6248:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6249:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6250:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6251:    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);
                   6252:    /*  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  6253:     */
1.218     brouard  6254:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6255:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6256: 
1.218     brouard  6257:    free_vector(xp,1,npar);
                   6258:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6259:    free_matrix(dnewm,1,nlstate,1,npar);
                   6260:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6261:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6262:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6263:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6264:    fclose(ficresprobmorprev);
                   6265:    fflush(ficgp);
                   6266:    fflush(fichtm); 
                   6267:  }  /* end varevsij */
1.126     brouard  6268: 
                   6269: /************ Variance of prevlim ******************/
1.269     brouard  6270:  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  6271: {
1.205     brouard  6272:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6273:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6274: 
1.268     brouard  6275:   double **dnewmpar,**doldm;
1.126     brouard  6276:   int i, j, nhstepm, hstepm;
                   6277:   double *xp;
                   6278:   double *gp, *gm;
                   6279:   double **gradg, **trgradg;
1.208     brouard  6280:   double **mgm, **mgp;
1.126     brouard  6281:   double age,agelim;
                   6282:   int theta;
                   6283:   
                   6284:   pstamp(ficresvpl);
1.288     brouard  6285:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6286:   fprintf(ficresvpl,"# Age ");
                   6287:   if(nresult >=1)
                   6288:     fprintf(ficresvpl," Result# ");
1.126     brouard  6289:   for(i=1; i<=nlstate;i++)
                   6290:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6291:   fprintf(ficresvpl,"\n");
                   6292: 
                   6293:   xp=vector(1,npar);
1.268     brouard  6294:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6295:   doldm=matrix(1,nlstate,1,nlstate);
                   6296:   
                   6297:   hstepm=1*YEARM; /* Every year of age */
                   6298:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6299:   agelim = AGESUP;
                   6300:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6301:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6302:     if (stepm >= YEARM) hstepm=1;
                   6303:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6304:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6305:     mgp=matrix(1,npar,1,nlstate);
                   6306:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6307:     gp=vector(1,nlstate);
                   6308:     gm=vector(1,nlstate);
                   6309: 
                   6310:     for(theta=1; theta <=npar; theta++){
                   6311:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6312:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6313:       }
1.288     brouard  6314:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6315:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6316:       /* else */
                   6317:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6318:       for(i=1;i<=nlstate;i++){
1.126     brouard  6319:        gp[i] = prlim[i][i];
1.208     brouard  6320:        mgp[theta][i] = prlim[i][i];
                   6321:       }
1.126     brouard  6322:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6323:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6324:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6325:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6326:       /* else */
                   6327:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6328:       for(i=1;i<=nlstate;i++){
1.126     brouard  6329:        gm[i] = prlim[i][i];
1.208     brouard  6330:        mgm[theta][i] = prlim[i][i];
                   6331:       }
1.126     brouard  6332:       for(i=1;i<=nlstate;i++)
                   6333:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6334:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6335:     } /* End theta */
                   6336: 
                   6337:     trgradg =matrix(1,nlstate,1,npar);
                   6338: 
                   6339:     for(j=1; j<=nlstate;j++)
                   6340:       for(theta=1; theta <=npar; theta++)
                   6341:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6342:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6343:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6344:     /*   for(j=1; j<=nlstate;j++){ */
                   6345:     /*         printf(" %d ",j); */
                   6346:     /*         for(theta=1; theta <=npar; theta++) */
                   6347:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6348:     /*         printf("\n "); */
                   6349:     /*   } */
                   6350:     /* } */
                   6351:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6352:     /*   printf("\n gradg %d ",(int)age); */
                   6353:     /*   for(j=1; j<=nlstate;j++){ */
                   6354:     /*         printf("%d ",j); */
                   6355:     /*         for(theta=1; theta <=npar; theta++) */
                   6356:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6357:     /*         printf("\n "); */
                   6358:     /*   } */
                   6359:     /* } */
1.126     brouard  6360: 
                   6361:     for(i=1;i<=nlstate;i++)
                   6362:       varpl[i][(int)age] =0.;
1.209     brouard  6363:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6364:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6365:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6366:     }else{
1.268     brouard  6367:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6368:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6369:     }
1.126     brouard  6370:     for(i=1;i<=nlstate;i++)
                   6371:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6372: 
                   6373:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6374:     if(nresult >=1)
                   6375:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6376:     for(i=1; i<=nlstate;i++){
1.126     brouard  6377:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6378:       /* for(j=1;j<=nlstate;j++) */
                   6379:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6380:     }
1.126     brouard  6381:     fprintf(ficresvpl,"\n");
                   6382:     free_vector(gp,1,nlstate);
                   6383:     free_vector(gm,1,nlstate);
1.208     brouard  6384:     free_matrix(mgm,1,npar,1,nlstate);
                   6385:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6386:     free_matrix(gradg,1,npar,1,nlstate);
                   6387:     free_matrix(trgradg,1,nlstate,1,npar);
                   6388:   } /* End age */
                   6389: 
                   6390:   free_vector(xp,1,npar);
                   6391:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6392:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6393: 
                   6394: }
                   6395: 
                   6396: 
                   6397: /************ Variance of backprevalence limit ******************/
1.269     brouard  6398:  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  6399: {
                   6400:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6401:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6402: 
                   6403:   double **dnewmpar,**doldm;
                   6404:   int i, j, nhstepm, hstepm;
                   6405:   double *xp;
                   6406:   double *gp, *gm;
                   6407:   double **gradg, **trgradg;
                   6408:   double **mgm, **mgp;
                   6409:   double age,agelim;
                   6410:   int theta;
                   6411:   
                   6412:   pstamp(ficresvbl);
                   6413:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6414:   fprintf(ficresvbl,"# Age ");
                   6415:   if(nresult >=1)
                   6416:     fprintf(ficresvbl," Result# ");
                   6417:   for(i=1; i<=nlstate;i++)
                   6418:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6419:   fprintf(ficresvbl,"\n");
                   6420: 
                   6421:   xp=vector(1,npar);
                   6422:   dnewmpar=matrix(1,nlstate,1,npar);
                   6423:   doldm=matrix(1,nlstate,1,nlstate);
                   6424:   
                   6425:   hstepm=1*YEARM; /* Every year of age */
                   6426:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6427:   agelim = AGEINF;
                   6428:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6429:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6430:     if (stepm >= YEARM) hstepm=1;
                   6431:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6432:     gradg=matrix(1,npar,1,nlstate);
                   6433:     mgp=matrix(1,npar,1,nlstate);
                   6434:     mgm=matrix(1,npar,1,nlstate);
                   6435:     gp=vector(1,nlstate);
                   6436:     gm=vector(1,nlstate);
                   6437: 
                   6438:     for(theta=1; theta <=npar; theta++){
                   6439:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6440:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6441:       }
                   6442:       if(mobilavproj > 0 )
                   6443:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6444:       else
                   6445:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6446:       for(i=1;i<=nlstate;i++){
                   6447:        gp[i] = bprlim[i][i];
                   6448:        mgp[theta][i] = bprlim[i][i];
                   6449:       }
                   6450:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6451:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6452:        if(mobilavproj > 0 )
                   6453:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6454:        else
                   6455:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6456:       for(i=1;i<=nlstate;i++){
                   6457:        gm[i] = bprlim[i][i];
                   6458:        mgm[theta][i] = bprlim[i][i];
                   6459:       }
                   6460:       for(i=1;i<=nlstate;i++)
                   6461:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6462:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6463:     } /* End theta */
                   6464: 
                   6465:     trgradg =matrix(1,nlstate,1,npar);
                   6466: 
                   6467:     for(j=1; j<=nlstate;j++)
                   6468:       for(theta=1; theta <=npar; theta++)
                   6469:        trgradg[j][theta]=gradg[theta][j];
                   6470:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6471:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6472:     /*   for(j=1; j<=nlstate;j++){ */
                   6473:     /*         printf(" %d ",j); */
                   6474:     /*         for(theta=1; theta <=npar; theta++) */
                   6475:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6476:     /*         printf("\n "); */
                   6477:     /*   } */
                   6478:     /* } */
                   6479:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6480:     /*   printf("\n gradg %d ",(int)age); */
                   6481:     /*   for(j=1; j<=nlstate;j++){ */
                   6482:     /*         printf("%d ",j); */
                   6483:     /*         for(theta=1; theta <=npar; theta++) */
                   6484:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6485:     /*         printf("\n "); */
                   6486:     /*   } */
                   6487:     /* } */
                   6488: 
                   6489:     for(i=1;i<=nlstate;i++)
                   6490:       varbpl[i][(int)age] =0.;
                   6491:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6492:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6493:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6494:     }else{
                   6495:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6496:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6497:     }
                   6498:     for(i=1;i<=nlstate;i++)
                   6499:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6500: 
                   6501:     fprintf(ficresvbl,"%.0f ",age );
                   6502:     if(nresult >=1)
                   6503:       fprintf(ficresvbl,"%d ",nres );
                   6504:     for(i=1; i<=nlstate;i++)
                   6505:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6506:     fprintf(ficresvbl,"\n");
                   6507:     free_vector(gp,1,nlstate);
                   6508:     free_vector(gm,1,nlstate);
                   6509:     free_matrix(mgm,1,npar,1,nlstate);
                   6510:     free_matrix(mgp,1,npar,1,nlstate);
                   6511:     free_matrix(gradg,1,npar,1,nlstate);
                   6512:     free_matrix(trgradg,1,nlstate,1,npar);
                   6513:   } /* End age */
                   6514: 
                   6515:   free_vector(xp,1,npar);
                   6516:   free_matrix(doldm,1,nlstate,1,npar);
                   6517:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6518: 
                   6519: }
                   6520: 
                   6521: /************ Variance of one-step probabilities  ******************/
                   6522: 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  6523:  {
                   6524:    int i, j=0,  k1, l1, tj;
                   6525:    int k2, l2, j1,  z1;
                   6526:    int k=0, l;
                   6527:    int first=1, first1, first2;
                   6528:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6529:    double **dnewm,**doldm;
                   6530:    double *xp;
                   6531:    double *gp, *gm;
                   6532:    double **gradg, **trgradg;
                   6533:    double **mu;
                   6534:    double age, cov[NCOVMAX+1];
                   6535:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6536:    int theta;
                   6537:    char fileresprob[FILENAMELENGTH];
                   6538:    char fileresprobcov[FILENAMELENGTH];
                   6539:    char fileresprobcor[FILENAMELENGTH];
                   6540:    double ***varpij;
                   6541: 
                   6542:    strcpy(fileresprob,"PROB_"); 
                   6543:    strcat(fileresprob,fileres);
                   6544:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6545:      printf("Problem with resultfile: %s\n", fileresprob);
                   6546:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6547:    }
                   6548:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6549:    strcat(fileresprobcov,fileresu);
                   6550:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6551:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6552:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6553:    }
                   6554:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6555:    strcat(fileresprobcor,fileresu);
                   6556:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6557:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6558:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6559:    }
                   6560:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6561:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6562:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6563:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6564:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6565:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6566:    pstamp(ficresprob);
                   6567:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6568:    fprintf(ficresprob,"# Age");
                   6569:    pstamp(ficresprobcov);
                   6570:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6571:    fprintf(ficresprobcov,"# Age");
                   6572:    pstamp(ficresprobcor);
                   6573:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6574:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6575: 
                   6576: 
1.222     brouard  6577:    for(i=1; i<=nlstate;i++)
                   6578:      for(j=1; j<=(nlstate+ndeath);j++){
                   6579:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6580:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6581:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6582:      }  
                   6583:    /* fprintf(ficresprob,"\n");
                   6584:       fprintf(ficresprobcov,"\n");
                   6585:       fprintf(ficresprobcor,"\n");
                   6586:    */
                   6587:    xp=vector(1,npar);
                   6588:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6589:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6590:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6591:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6592:    first=1;
                   6593:    fprintf(ficgp,"\n# Routine varprob");
                   6594:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6595:    fprintf(fichtm,"\n");
                   6596: 
1.288     brouard  6597:    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  6598:    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);
                   6599:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6600: and drawn. It helps understanding how is the covariance between two incidences.\
                   6601:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6602:    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  6603: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6604: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6605: standard deviations wide on each axis. <br>\
                   6606:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6607:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6608: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6609: 
1.222     brouard  6610:    cov[1]=1;
                   6611:    /* tj=cptcoveff; */
1.225     brouard  6612:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6613:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6614:    j1=0;
1.224     brouard  6615:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6616:      if  (cptcovn>0) {
                   6617:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6618:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6619:        fprintf(ficresprob, "**********\n#\n");
                   6620:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6621:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6622:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6623:                        
1.222     brouard  6624:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6625:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6626:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6627:                        
                   6628:                        
1.222     brouard  6629:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6630:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6631:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6632:                        
1.222     brouard  6633:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6634:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6635:        fprintf(ficresprobcor, "**********\n#");    
                   6636:        if(invalidvarcomb[j1]){
                   6637:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6638:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6639:         continue;
                   6640:        }
                   6641:      }
                   6642:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6643:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6644:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6645:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6646:      for (age=bage; age<=fage; age ++){ 
                   6647:        cov[2]=age;
                   6648:        if(nagesqr==1)
                   6649:         cov[3]= age*age;
                   6650:        for (k=1; k<=cptcovn;k++) {
                   6651:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6652:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6653:                                                                    * 1  1 1 1 1
                   6654:                                                                    * 2  2 1 1 1
                   6655:                                                                    * 3  1 2 1 1
                   6656:                                                                    */
                   6657:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6658:        }
                   6659:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6660:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6661:        for (k=1; k<=cptcovprod;k++)
                   6662:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6663:                        
                   6664:                        
1.222     brouard  6665:        for(theta=1; theta <=npar; theta++){
                   6666:         for(i=1; i<=npar; i++)
                   6667:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6668:                                
1.222     brouard  6669:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6670:                                
1.222     brouard  6671:         k=0;
                   6672:         for(i=1; i<= (nlstate); i++){
                   6673:           for(j=1; j<=(nlstate+ndeath);j++){
                   6674:             k=k+1;
                   6675:             gp[k]=pmmij[i][j];
                   6676:           }
                   6677:         }
1.220     brouard  6678:                                
1.222     brouard  6679:         for(i=1; i<=npar; i++)
                   6680:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6681:                                
1.222     brouard  6682:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6683:         k=0;
                   6684:         for(i=1; i<=(nlstate); i++){
                   6685:           for(j=1; j<=(nlstate+ndeath);j++){
                   6686:             k=k+1;
                   6687:             gm[k]=pmmij[i][j];
                   6688:           }
                   6689:         }
1.220     brouard  6690:                                
1.222     brouard  6691:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6692:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6693:        }
1.126     brouard  6694: 
1.222     brouard  6695:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6696:         for(theta=1; theta <=npar; theta++)
                   6697:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6698:                        
1.222     brouard  6699:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6700:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6701:                        
1.222     brouard  6702:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6703:                        
1.222     brouard  6704:        k=0;
                   6705:        for(i=1; i<=(nlstate); i++){
                   6706:         for(j=1; j<=(nlstate+ndeath);j++){
                   6707:           k=k+1;
                   6708:           mu[k][(int) age]=pmmij[i][j];
                   6709:         }
                   6710:        }
                   6711:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6712:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6713:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6714:                        
1.222     brouard  6715:        /*printf("\n%d ",(int)age);
                   6716:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6717:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6718:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6719:         }*/
1.220     brouard  6720:                        
1.222     brouard  6721:        fprintf(ficresprob,"\n%d ",(int)age);
                   6722:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6723:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6724:                        
1.222     brouard  6725:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6726:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6727:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6728:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6729:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6730:        }
                   6731:        i=0;
                   6732:        for (k=1; k<=(nlstate);k++){
                   6733:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6734:           i++;
                   6735:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6736:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6737:           for (j=1; j<=i;j++){
                   6738:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6739:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6740:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6741:           }
                   6742:         }
                   6743:        }/* end of loop for state */
                   6744:      } /* end of loop for age */
                   6745:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6746:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6747:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6748:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6749:     
                   6750:      /* Confidence intervalle of pij  */
                   6751:      /*
                   6752:        fprintf(ficgp,"\nunset parametric;unset label");
                   6753:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6754:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6755:        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);
                   6756:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6757:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6758:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6759:      */
                   6760:                
                   6761:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6762:      first1=1;first2=2;
                   6763:      for (k2=1; k2<=(nlstate);k2++){
                   6764:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6765:         if(l2==k2) continue;
                   6766:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6767:         for (k1=1; k1<=(nlstate);k1++){
                   6768:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6769:             if(l1==k1) continue;
                   6770:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6771:             if(i<=j) continue;
                   6772:             for (age=bage; age<=fage; age ++){ 
                   6773:               if ((int)age %5==0){
                   6774:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6775:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6776:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6777:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6778:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6779:                 c12=cv12/sqrt(v1*v2);
                   6780:                 /* Computing eigen value of matrix of covariance */
                   6781:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6782:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6783:                 if ((lc2 <0) || (lc1 <0) ){
                   6784:                   if(first2==1){
                   6785:                     first1=0;
                   6786:                     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);
                   6787:                   }
                   6788:                   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);
                   6789:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6790:                   /* lc2=fabs(lc2); */
                   6791:                 }
1.220     brouard  6792:                                                                
1.222     brouard  6793:                 /* Eigen vectors */
1.280     brouard  6794:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6795:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6796:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6797:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6798:                 }else
                   6799:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6800:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6801:                 v21=(lc1-v1)/cv12*v11;
                   6802:                 v12=-v21;
                   6803:                 v22=v11;
                   6804:                 tnalp=v21/v11;
                   6805:                 if(first1==1){
                   6806:                   first1=0;
                   6807:                   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);
                   6808:                 }
                   6809:                 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);
                   6810:                 /*printf(fignu*/
                   6811:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6812:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6813:                 if(first==1){
                   6814:                   first=0;
                   6815:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6816:                   fprintf(ficgp,"\nset parametric;unset label");
                   6817:                   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);
                   6818:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6819:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6820:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6821: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6822:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6823:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6824:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6825:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6826:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6827:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6828:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6829:                   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  6830:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6831:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6832:                 }else{
                   6833:                   first=0;
                   6834:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6835:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6836:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6837:                   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  6838:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6839:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6840:                 }/* if first */
                   6841:               } /* age mod 5 */
                   6842:             } /* end loop age */
                   6843:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6844:             first=1;
                   6845:           } /*l12 */
                   6846:         } /* k12 */
                   6847:        } /*l1 */
                   6848:      }/* k1 */
                   6849:    }  /* loop on combination of covariates j1 */
                   6850:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6851:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6852:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6853:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6854:    free_vector(xp,1,npar);
                   6855:    fclose(ficresprob);
                   6856:    fclose(ficresprobcov);
                   6857:    fclose(ficresprobcor);
                   6858:    fflush(ficgp);
                   6859:    fflush(fichtmcov);
                   6860:  }
1.126     brouard  6861: 
                   6862: 
                   6863: /******************* Printing html file ***********/
1.201     brouard  6864: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6865:                  int lastpass, int stepm, int weightopt, char model[],\
                   6866:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  6867:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   6868:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   6869:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  6870:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6871: 
                   6872:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6873:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6874: </ul>");
1.237     brouard  6875:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6876: </ul>", model);
1.214     brouard  6877:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6878:    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",
                   6879:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6880:    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  6881:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6882:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6883:    fprintf(fichtm,"\
                   6884:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6885:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6886:    fprintf(fichtm,"\
1.217     brouard  6887:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6888:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6889:    fprintf(fichtm,"\
1.288     brouard  6890:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6891:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6892:    fprintf(fichtm,"\
1.288     brouard  6893:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6894:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6895:    fprintf(fichtm,"\
1.211     brouard  6896:  - (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  6897:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6898:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6899:    if(prevfcast==1){
                   6900:      fprintf(fichtm,"\
                   6901:  - Prevalence projections by age and states:                           \
1.201     brouard  6902:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6903:    }
1.126     brouard  6904: 
                   6905: 
1.225     brouard  6906:    m=pow(2,cptcoveff);
1.222     brouard  6907:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6908: 
1.264     brouard  6909:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6910: 
                   6911:    jj1=0;
                   6912: 
                   6913:    fprintf(fichtm," \n<ul>");
                   6914:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6915:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6916:      if(m != 1 && TKresult[nres]!= k1)
                   6917:        continue;
                   6918:      jj1++;
                   6919:      if (cptcovn > 0) {
                   6920:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6921:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6922:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6923:        }
                   6924:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6925:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6926:        }
                   6927:        fprintf(fichtm,"\">");
                   6928:        
                   6929:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   6930:        fprintf(fichtm,"************ Results for covariates");
                   6931:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6932:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6933:        }
                   6934:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6935:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6936:        }
                   6937:        if(invalidvarcomb[k1]){
                   6938:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   6939:         continue;
                   6940:        }
                   6941:        fprintf(fichtm,"</a></li>");
                   6942:      } /* cptcovn >0 */
                   6943:    }
                   6944:      fprintf(fichtm," \n</ul>");
                   6945: 
1.222     brouard  6946:    jj1=0;
1.237     brouard  6947: 
                   6948:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6949:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6950:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6951:        continue;
1.220     brouard  6952: 
1.222     brouard  6953:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6954:      jj1++;
                   6955:      if (cptcovn > 0) {
1.264     brouard  6956:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   6957:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6958:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6959:        }
                   6960:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6961:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6962:        }
                   6963:        fprintf(fichtm,"\"</a>");
                   6964:  
1.222     brouard  6965:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6966:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6967:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6968:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6969:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6970:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6971:        }
1.237     brouard  6972:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6973:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6974:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6975:       }
                   6976:        
1.230     brouard  6977:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6978:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6979:        if(invalidvarcomb[k1]){
                   6980:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6981:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6982:         continue;
                   6983:        }
                   6984:      }
                   6985:      /* aij, bij */
1.259     brouard  6986:      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  6987: <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  6988:      /* Pij */
1.241     brouard  6989:      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> \
                   6990: <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  6991:      /* Quasi-incidences */
                   6992:      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  6993:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6994:  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  6995: 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> \
                   6996: <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  6997:      /* Survival functions (period) in state j */
                   6998:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6999:        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  7000: <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  7001:      }
                   7002:      /* State specific survival functions (period) */
                   7003:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7004:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7005:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7006:  <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  7007:      }
1.288     brouard  7008:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7009:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7010:        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> \
                   7011: <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  7012:      }
1.296     brouard  7013:      if(prevbcast==1){
1.288     brouard  7014:        /* Backward prevalence in each health state */
1.222     brouard  7015:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7016:         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  7017: <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  7018:        }
1.217     brouard  7019:      }
1.222     brouard  7020:      if(prevfcast==1){
1.288     brouard  7021:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7022:        for(cpt=1; cpt<=nlstate;cpt++){
1.288     brouard  7023:         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><br> \
1.296     brouard  7024: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, mobilavproj, dateprojd, dateprojf, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7025:        }
                   7026:      }
1.296     brouard  7027:      if(prevbcast==1){
1.268     brouard  7028:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7029:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7030:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7031:  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 \
                   7032:  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) \
                   7033: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   7034:  <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, mobilavproj, dateback1, dateback2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7035:        }
                   7036:      }
1.220     brouard  7037:         
1.222     brouard  7038:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  7039:        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> <br> \
                   7040: <img src=\"%s_%d-%d-%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.222     brouard  7041:      }
                   7042:      /* } /\* end i1 *\/ */
                   7043:    }/* End k1 */
                   7044:    fprintf(fichtm,"</ul>");
1.126     brouard  7045: 
1.222     brouard  7046:    fprintf(fichtm,"\
1.126     brouard  7047: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7048:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7049:  - 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  7050: But because parameters are usually highly correlated (a higher incidence of disability \
                   7051: and a higher incidence of recovery can give very close observed transition) it might \
                   7052: be very useful to look not only at linear confidence intervals estimated from the \
                   7053: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7054: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7055: covariance matrix of the one-step probabilities. \
                   7056: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7057: 
1.222     brouard  7058:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7059:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7060:    fprintf(fichtm,"\
1.126     brouard  7061:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7062:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7063: 
1.222     brouard  7064:    fprintf(fichtm,"\
1.126     brouard  7065:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7066:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7067:    fprintf(fichtm,"\
1.126     brouard  7068:  - 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): \
                   7069:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7070:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7071:    fprintf(fichtm,"\
1.126     brouard  7072:  - (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): \
                   7073:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7074:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7075:    fprintf(fichtm,"\
1.288     brouard  7076:  - 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  7077:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7078:    fprintf(fichtm,"\
1.128     brouard  7079:  - 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  7080:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7081:    fprintf(fichtm,"\
1.288     brouard  7082:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7083:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7084: 
                   7085: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7086: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7087: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7088: /*     <br>",fileres,fileres,fileres,fileres); */
                   7089: /*  else  */
                   7090: /*    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  7091:    fflush(fichtm);
                   7092:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7093: 
1.225     brouard  7094:    m=pow(2,cptcoveff);
1.222     brouard  7095:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7096: 
1.222     brouard  7097:    jj1=0;
1.237     brouard  7098: 
1.241     brouard  7099:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7100:    for(k1=1; k1<=m;k1++){
1.253     brouard  7101:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7102:        continue;
1.222     brouard  7103:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7104:      jj1++;
1.126     brouard  7105:      if (cptcovn > 0) {
                   7106:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7107:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7108:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7109:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7110:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7111:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7112:       }
                   7113: 
1.126     brouard  7114:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7115: 
1.222     brouard  7116:        if(invalidvarcomb[k1]){
                   7117:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7118:         continue;
                   7119:        }
1.126     brouard  7120:      }
                   7121:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7122:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  7123: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
1.258     brouard  7124: <img src=\"%s_%d-%d-%d.svg\">",mobilav,cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);  
1.126     brouard  7125:      }
                   7126:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  7127: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   7128: true period expectancies (those weighted with period prevalences are also\
                   7129:  drawn in addition to the population based expectancies computed using\
1.241     brouard  7130:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   7131: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7132:      /* } /\* end i1 *\/ */
                   7133:    }/* End k1 */
1.241     brouard  7134:   }/* End nres */
1.222     brouard  7135:    fprintf(fichtm,"</ul>");
                   7136:    fflush(fichtm);
1.126     brouard  7137: }
                   7138: 
                   7139: /******************* Gnuplot file **************/
1.296     brouard  7140: 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  7141: 
                   7142:   char dirfileres[132],optfileres[132];
1.264     brouard  7143:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7144:   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  7145:   int lv=0, vlv=0, kl=0;
1.130     brouard  7146:   int ng=0;
1.201     brouard  7147:   int vpopbased;
1.223     brouard  7148:   int ioffset; /* variable offset for columns */
1.270     brouard  7149:   int iyearc=1; /* variable column for year of projection  */
                   7150:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7151:   int nres=0; /* Index of resultline */
1.266     brouard  7152:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7153: 
1.126     brouard  7154: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7155: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7156: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7157: /*   } */
                   7158: 
                   7159:   /*#ifdef windows */
                   7160:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7161:   /*#endif */
1.225     brouard  7162:   m=pow(2,cptcoveff);
1.126     brouard  7163: 
1.274     brouard  7164:   /* diagram of the model */
                   7165:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7166:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7167:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7168:   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);
                   7169: 
                   7170:   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);
                   7171:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7172:   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);
                   7173:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7174:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7175:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7176:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7177: 
1.202     brouard  7178:   /* Contribution to likelihood */
                   7179:   /* Plot the probability implied in the likelihood */
1.223     brouard  7180:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7181:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7182:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7183:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7184: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7185:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7186: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7187:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7188:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7189:   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));
                   7190:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7191:   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));
                   7192:   for (i=1; i<= nlstate ; i ++) {
                   7193:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7194:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7195:     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);
                   7196:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7197:       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);
                   7198:     }
                   7199:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7200:   }
                   7201:   /* 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 */               
                   7202:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7203:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7204:   fprintf(ficgp,"\nset out;unset log\n");
                   7205:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7206: 
1.126     brouard  7207:   strcpy(dirfileres,optionfilefiname);
                   7208:   strcpy(optfileres,"vpl");
1.223     brouard  7209:   /* 1eme*/
1.238     brouard  7210:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7211:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7212:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7213:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7214:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7215:          continue;
                   7216:        /* We are interested in selected combination by the resultline */
1.246     brouard  7217:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7218:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7219:        strcpy(gplotlabel,"(");
1.238     brouard  7220:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7221:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7222:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7223:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7224:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7225:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7226:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7227:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7228:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7229:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7230:        }
                   7231:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7232:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7233:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7234:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7235:        }
                   7236:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7237:        /* printf("\n#\n"); */
1.238     brouard  7238:        fprintf(ficgp,"\n#\n");
                   7239:        if(invalidvarcomb[k1]){
1.260     brouard  7240:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7241:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7242:          continue;
                   7243:        }
1.235     brouard  7244:       
1.241     brouard  7245:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7246:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7247:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7248:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7249:        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);
                   7250:        /* 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); */
                   7251:       /* k1-1 error should be nres-1*/
1.238     brouard  7252:        for (i=1; i<= nlstate ; i ++) {
                   7253:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7254:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7255:        }
1.288     brouard  7256:        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  7257:        for (i=1; i<= nlstate ; i ++) {
                   7258:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7259:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7260:        } 
1.260     brouard  7261:        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  7262:        for (i=1; i<= nlstate ; i ++) {
                   7263:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7264:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7265:        }  
1.265     brouard  7266:        /* 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)); */
                   7267:        
                   7268:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7269:         if(cptcoveff ==0){
1.271     brouard  7270:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7271:        }else{
                   7272:          kl=0;
                   7273:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7274:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7275:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7276:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7277:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7278:            vlv= nbcode[Tvaraff[k]][lv];
                   7279:            kl++;
                   7280:            /* 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 *\/ */
                   7281:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7282:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7283:            /* ''  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*/
                   7284:            if(k==cptcoveff){
                   7285:              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], \
                   7286:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7287:            }else{
                   7288:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7289:              kl++;
                   7290:            }
                   7291:          } /* end covariate */
                   7292:        } /* end if no covariate */
                   7293: 
1.296     brouard  7294:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7295:          /* 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  7296:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7297:          if(cptcoveff ==0){
1.245     brouard  7298:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7299:          }else{
                   7300:            kl=0;
                   7301:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7302:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7303:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7304:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7305:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7306:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7307:              kl++;
1.238     brouard  7308:              /* 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 *\/ */
                   7309:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7310:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7311:              /* ''  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*/
                   7312:              if(k==cptcoveff){
1.245     brouard  7313:                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  7314:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7315:              }else{
                   7316:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7317:                kl++;
                   7318:              }
                   7319:            } /* end covariate */
                   7320:          } /* end if no covariate */
1.296     brouard  7321:          if(prevbcast == 1){
1.268     brouard  7322:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7323:            /* k1-1 error should be nres-1*/
                   7324:            for (i=1; i<= nlstate ; i ++) {
                   7325:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7326:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7327:            }
1.271     brouard  7328:            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  7329:            for (i=1; i<= nlstate ; i ++) {
                   7330:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7331:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7332:            } 
1.276     brouard  7333:            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  7334:            for (i=1; i<= nlstate ; i ++) {
                   7335:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7336:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7337:            } 
1.274     brouard  7338:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7339:          } /* end if backprojcast */
1.296     brouard  7340:        } /* end if prevbcast */
1.276     brouard  7341:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7342:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7343:       } /* nres */
1.201     brouard  7344:     } /* k1 */
                   7345:   } /* cpt */
1.235     brouard  7346: 
                   7347:   
1.126     brouard  7348:   /*2 eme*/
1.238     brouard  7349:   for (k1=1; k1<= m ; k1 ++){  
                   7350:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7351:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7352:        continue;
                   7353:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7354:       strcpy(gplotlabel,"(");
1.238     brouard  7355:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7356:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7357:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7358:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7359:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7360:        vlv= nbcode[Tvaraff[k]][lv];
                   7361:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7362:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7363:       }
1.237     brouard  7364:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7365:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7366:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7367:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7368:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7369:       }
1.264     brouard  7370:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7371:       fprintf(ficgp,"\n#\n");
1.223     brouard  7372:       if(invalidvarcomb[k1]){
                   7373:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7374:        continue;
                   7375:       }
1.219     brouard  7376:                        
1.241     brouard  7377:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7378:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7379:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7380:        if(vpopbased==0){
1.238     brouard  7381:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7382:        }else
1.238     brouard  7383:          fprintf(ficgp,"\nreplot ");
                   7384:        for (i=1; i<= nlstate+1 ; i ++) {
                   7385:          k=2*i;
1.261     brouard  7386:          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  7387:          for (j=1; j<= nlstate+1 ; j ++) {
                   7388:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7389:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7390:          }   
                   7391:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7392:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7393:          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  7394:          for (j=1; j<= nlstate+1 ; j ++) {
                   7395:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7396:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7397:          }   
                   7398:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7399:          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  7400:          for (j=1; j<= nlstate+1 ; j ++) {
                   7401:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7402:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7403:          }   
                   7404:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7405:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7406:        } /* state */
                   7407:       } /* vpopbased */
1.264     brouard  7408:       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  7409:     } /* end nres */
                   7410:   } /* k1 end 2 eme*/
                   7411:        
                   7412:        
                   7413:   /*3eme*/
                   7414:   for (k1=1; k1<= m ; k1 ++){
                   7415:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7416:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7417:        continue;
                   7418: 
                   7419:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7420:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7421:        strcpy(gplotlabel,"(");
1.238     brouard  7422:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7423:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7424:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7425:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7426:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7427:          vlv= nbcode[Tvaraff[k]][lv];
                   7428:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7429:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7430:        }
                   7431:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7432:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7433:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7434:        }       
1.264     brouard  7435:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7436:        fprintf(ficgp,"\n#\n");
                   7437:        if(invalidvarcomb[k1]){
                   7438:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7439:          continue;
                   7440:        }
                   7441:                        
                   7442:        /*       k=2+nlstate*(2*cpt-2); */
                   7443:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7444:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7445:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7446:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7447: 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  7448:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7449:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7450:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7451:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7452:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7453:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7454:                                
1.238     brouard  7455:        */
                   7456:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7457:          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  7458:          /*    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  7459:                                
1.238     brouard  7460:        } 
1.261     brouard  7461:        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  7462:       }
1.264     brouard  7463:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7464:     } /* end nres */
                   7465:   } /* end kl 3eme */
1.126     brouard  7466:   
1.223     brouard  7467:   /* 4eme */
1.201     brouard  7468:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7469:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7470:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7471:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7472:        continue;
1.238     brouard  7473:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7474:        strcpy(gplotlabel,"(");
1.238     brouard  7475:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7476:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7477:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7478:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7479:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7480:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7481:          vlv= nbcode[Tvaraff[k]][lv];
                   7482:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7483:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7484:        }
                   7485:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7486:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7487:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7488:        }       
1.264     brouard  7489:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7490:        fprintf(ficgp,"\n#\n");
                   7491:        if(invalidvarcomb[k1]){
                   7492:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7493:          continue;
1.223     brouard  7494:        }
1.238     brouard  7495:       
1.241     brouard  7496:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7497:        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  7498:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7499: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7500:        k=3;
                   7501:        for (i=1; i<= nlstate ; i ++){
                   7502:          if(i==1){
                   7503:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7504:          }else{
                   7505:            fprintf(ficgp,", '' ");
                   7506:          }
                   7507:          l=(nlstate+ndeath)*(i-1)+1;
                   7508:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7509:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7510:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7511:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7512:        } /* nlstate */
1.264     brouard  7513:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7514:       } /* end cpt state*/ 
                   7515:     } /* end nres */
                   7516:   } /* end covariate k1 */  
                   7517: 
1.220     brouard  7518: /* 5eme */
1.201     brouard  7519:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7520:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7521:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7522:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7523:        continue;
1.238     brouard  7524:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7525:        strcpy(gplotlabel,"(");
1.238     brouard  7526:        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);
                   7527:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7528:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7529:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7530:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7531:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7532:          vlv= nbcode[Tvaraff[k]][lv];
                   7533:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7534:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7535:        }
                   7536:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7537:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7538:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7539:        }       
1.264     brouard  7540:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7541:        fprintf(ficgp,"\n#\n");
                   7542:        if(invalidvarcomb[k1]){
                   7543:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7544:          continue;
                   7545:        }
1.227     brouard  7546:       
1.241     brouard  7547:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7548:        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  7549:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7550: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7551:        k=3;
                   7552:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7553:          if(j==1)
                   7554:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7555:          else
                   7556:            fprintf(ficgp,", '' ");
                   7557:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7558:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7559:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7560:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7561:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7562:        } /* nlstate */
                   7563:        fprintf(ficgp,", '' ");
                   7564:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7565:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7566:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7567:          if(j < nlstate)
                   7568:            fprintf(ficgp,"$%d +",k+l);
                   7569:          else
                   7570:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7571:        }
1.264     brouard  7572:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7573:       } /* end cpt state*/ 
                   7574:     } /* end covariate */  
                   7575:   } /* end nres */
1.227     brouard  7576:   
1.220     brouard  7577: /* 6eme */
1.202     brouard  7578:   /* CV preval stable (period) for each covariate */
1.237     brouard  7579:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7580:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7581:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7582:       continue;
1.255     brouard  7583:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7584:       strcpy(gplotlabel,"(");      
1.288     brouard  7585:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7586:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7587:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7588:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7589:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7590:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7591:        vlv= nbcode[Tvaraff[k]][lv];
                   7592:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7593:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7594:       }
1.237     brouard  7595:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7596:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7597:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7598:       }        
1.264     brouard  7599:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7600:       fprintf(ficgp,"\n#\n");
1.223     brouard  7601:       if(invalidvarcomb[k1]){
1.227     brouard  7602:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7603:        continue;
1.223     brouard  7604:       }
1.227     brouard  7605:       
1.241     brouard  7606:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7607:       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  7608:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7609: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7610:       k=3; /* Offset */
1.255     brouard  7611:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7612:        if(i==1)
                   7613:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7614:        else
                   7615:          fprintf(ficgp,", '' ");
1.255     brouard  7616:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7617:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7618:        for (j=2; j<= nlstate ; j ++)
                   7619:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7620:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7621:       } /* nlstate */
1.264     brouard  7622:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7623:     } /* end cpt state*/ 
                   7624:   } /* end covariate */  
1.227     brouard  7625:   
                   7626:   
1.220     brouard  7627: /* 7eme */
1.296     brouard  7628:   if(prevbcast == 1){
1.288     brouard  7629:     /* CV backward prevalence  for each covariate */
1.237     brouard  7630:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7631:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7632:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7633:        continue;
1.268     brouard  7634:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7635:        strcpy(gplotlabel,"(");      
1.288     brouard  7636:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7637:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7638:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7639:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7640:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7641:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7642:          vlv= nbcode[Tvaraff[k]][lv];
                   7643:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7644:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7645:        }
1.237     brouard  7646:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7647:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7648:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7649:        }       
1.264     brouard  7650:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7651:        fprintf(ficgp,"\n#\n");
                   7652:        if(invalidvarcomb[k1]){
                   7653:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7654:          continue;
                   7655:        }
                   7656:        
1.241     brouard  7657:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7658:        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  7659:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7660: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7661:        k=3; /* Offset */
1.268     brouard  7662:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7663:          if(i==1)
                   7664:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7665:          else
                   7666:            fprintf(ficgp,", '' ");
                   7667:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7668:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7669:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7670:          /* 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  7671:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7672:          /* for (j=2; j<= nlstate ; j ++) */
                   7673:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7674:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7675:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7676:        } /* nlstate */
1.264     brouard  7677:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7678:       } /* end cpt state*/ 
                   7679:     } /* end covariate */  
1.296     brouard  7680:   } /* End if prevbcast */
1.218     brouard  7681:   
1.223     brouard  7682:   /* 8eme */
1.218     brouard  7683:   if(prevfcast==1){
1.288     brouard  7684:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7685:     
1.237     brouard  7686:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7687:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7688:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7689:        continue;
1.211     brouard  7690:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7691:        strcpy(gplotlabel,"(");      
1.288     brouard  7692:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7693:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7694:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7695:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7696:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7697:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7698:          vlv= nbcode[Tvaraff[k]][lv];
                   7699:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7700:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7701:        }
1.237     brouard  7702:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7703:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7704:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7705:        }       
1.264     brouard  7706:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7707:        fprintf(ficgp,"\n#\n");
                   7708:        if(invalidvarcomb[k1]){
                   7709:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7710:          continue;
                   7711:        }
                   7712:        
                   7713:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7714:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7715:        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  7716:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7717: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7718: 
                   7719:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7720:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7721:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7722:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7723:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7724:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7725:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7726:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7727:          if(i==istart){
1.227     brouard  7728:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7729:          }else{
                   7730:            fprintf(ficgp,",\\\n '' ");
                   7731:          }
                   7732:          if(cptcoveff ==0){ /* No covariate */
                   7733:            ioffset=2; /* Age is in 2 */
                   7734:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7735:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7736:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7737:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7738:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7739:            if(i==nlstate+1){
1.270     brouard  7740:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7741:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7742:              fprintf(ficgp,",\\\n '' ");
                   7743:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7744:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7745:                     offyear,                           \
1.268     brouard  7746:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7747:            }else
1.227     brouard  7748:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7749:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7750:          }else{ /* more than 2 covariates */
1.270     brouard  7751:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7752:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7753:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7754:            iyearc=ioffset-1;
                   7755:            iagec=ioffset;
1.227     brouard  7756:            fprintf(ficgp," u %d:(",ioffset); 
                   7757:            kl=0;
                   7758:            strcpy(gplotcondition,"(");
                   7759:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7760:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7761:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7762:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7763:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7764:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7765:              kl++;
                   7766:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7767:              kl++;
                   7768:              if(k <cptcoveff && cptcoveff>1)
                   7769:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7770:            }
                   7771:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7772:            /* 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 *\/ */
                   7773:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7774:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7775:            /* ''  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*/
                   7776:            if(i==nlstate+1){
1.270     brouard  7777:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7778:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7779:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7780:              fprintf(ficgp," u %d:(",iagec); 
                   7781:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7782:                      iyearc, iagec, offyear,                           \
                   7783:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7784: /*  '' 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  7785:            }else{
                   7786:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7787:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7788:            }
                   7789:          } /* end if covariate */
                   7790:        } /* nlstate */
1.264     brouard  7791:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7792:       } /* end cpt state*/
                   7793:     } /* end covariate */
                   7794:   } /* End if prevfcast */
1.227     brouard  7795:   
1.296     brouard  7796:   if(prevbcast==1){
1.268     brouard  7797:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7798:     
                   7799:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7800:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7801:       if(m != 1 && TKresult[nres]!= k1)
                   7802:        continue;
                   7803:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7804:        strcpy(gplotlabel,"(");      
                   7805:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7806:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7807:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7808:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7809:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7810:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7811:          vlv= nbcode[Tvaraff[k]][lv];
                   7812:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7813:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7814:        }
                   7815:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7816:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7817:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7818:        }       
                   7819:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7820:        fprintf(ficgp,"\n#\n");
                   7821:        if(invalidvarcomb[k1]){
                   7822:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7823:          continue;
                   7824:        }
                   7825:        
                   7826:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7827:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7828:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7829:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7830: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7831: 
                   7832:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7833:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7834:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7835:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7836:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7837:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7838:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7839:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7840:          if(i==istart){
                   7841:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7842:          }else{
                   7843:            fprintf(ficgp,",\\\n '' ");
                   7844:          }
                   7845:          if(cptcoveff ==0){ /* No covariate */
                   7846:            ioffset=2; /* Age is in 2 */
                   7847:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7848:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7849:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7850:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7851:            fprintf(ficgp," u %d:(", ioffset); 
                   7852:            if(i==nlstate+1){
1.270     brouard  7853:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7854:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7855:              fprintf(ficgp,",\\\n '' ");
                   7856:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7857:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7858:                     offbyear,                          \
                   7859:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7860:            }else
                   7861:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7862:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7863:          }else{ /* more than 2 covariates */
1.270     brouard  7864:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7865:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7866:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7867:            iyearc=ioffset-1;
                   7868:            iagec=ioffset;
1.268     brouard  7869:            fprintf(ficgp," u %d:(",ioffset); 
                   7870:            kl=0;
                   7871:            strcpy(gplotcondition,"(");
                   7872:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7873:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7874:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7875:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7876:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7877:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7878:              kl++;
                   7879:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7880:              kl++;
                   7881:              if(k <cptcoveff && cptcoveff>1)
                   7882:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7883:            }
                   7884:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7885:            /* 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 *\/ */
                   7886:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7887:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7888:            /* ''  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*/
                   7889:            if(i==nlstate+1){
1.270     brouard  7890:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7891:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7892:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7893:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7894:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7895:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7896:                      iyearc,iagec,offbyear,                            \
                   7897:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7898: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7899:            }else{
                   7900:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7901:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7902:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7903:            }
                   7904:          } /* end if covariate */
                   7905:        } /* nlstate */
                   7906:        fprintf(ficgp,"\nset out; unset label;\n");
                   7907:       } /* end cpt state*/
                   7908:     } /* end covariate */
1.296     brouard  7909:   } /* End if prevbcast */
1.268     brouard  7910:   
1.227     brouard  7911:   
1.238     brouard  7912:   /* 9eme writing MLE parameters */
                   7913:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7914:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7915:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7916:     for(k=1; k <=(nlstate+ndeath); k++){
                   7917:       if (k != i) {
1.227     brouard  7918:        fprintf(ficgp,"#   current state %d\n",k);
                   7919:        for(j=1; j <=ncovmodel; j++){
                   7920:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7921:          jk++; 
                   7922:        }
                   7923:        fprintf(ficgp,"\n");
1.126     brouard  7924:       }
                   7925:     }
1.223     brouard  7926:   }
1.187     brouard  7927:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7928:   
1.145     brouard  7929:   /*goto avoid;*/
1.238     brouard  7930:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7931:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7932:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7933:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7934:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7935:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7936:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7937:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7938:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7939:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7940:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7941:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7942:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7943:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7944:   fprintf(ficgp,"#\n");
1.223     brouard  7945:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7946:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7947:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7948:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  7949:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7950:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  7951:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  7952:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7953:        continue;
1.264     brouard  7954:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   7955:       strcpy(gplotlabel,"(");
1.276     brouard  7956:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  7957:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7958:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7959:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7960:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7961:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7962:        vlv= nbcode[Tvaraff[k]][lv];
                   7963:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7964:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7965:       }
1.237     brouard  7966:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7967:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7968:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7969:       }        
1.264     brouard  7970:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  7971:       fprintf(ficgp,"\n#\n");
1.264     brouard  7972:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  7973:       fprintf(ficgp,"\nset key outside ");
                   7974:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   7975:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  7976:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7977:       if (ng==1){
                   7978:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7979:        fprintf(ficgp,"\nunset log y");
                   7980:       }else if (ng==2){
                   7981:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7982:        fprintf(ficgp,"\nset log y");
                   7983:       }else if (ng==3){
                   7984:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7985:        fprintf(ficgp,"\nset log y");
                   7986:       }else
                   7987:        fprintf(ficgp,"\nunset title ");
                   7988:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7989:       i=1;
                   7990:       for(k2=1; k2<=nlstate; k2++) {
                   7991:        k3=i;
                   7992:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7993:          if (k != k2){
                   7994:            switch( ng) {
                   7995:            case 1:
                   7996:              if(nagesqr==0)
                   7997:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7998:              else /* nagesqr =1 */
                   7999:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8000:              break;
                   8001:            case 2: /* ng=2 */
                   8002:              if(nagesqr==0)
                   8003:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8004:              else /* nagesqr =1 */
                   8005:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8006:              break;
                   8007:            case 3:
                   8008:              if(nagesqr==0)
                   8009:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8010:              else /* nagesqr =1 */
                   8011:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8012:              break;
                   8013:            }
                   8014:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8015:            ijp=1; /* product no age */
                   8016:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8017:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8018:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8019:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8020:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8021:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8022:                    if(DummyV[j]==0){
                   8023:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8024:                    }else{ /* quantitative */
                   8025:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8026:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8027:                    }
                   8028:                    ij++;
1.237     brouard  8029:                  }
1.268     brouard  8030:                } 
                   8031:              }else if(cptcovprod >0){
                   8032:                if(j==Tprod[ijp]) { /* */ 
                   8033:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8034:                  if(ijp <=cptcovprod) { /* Product */
                   8035:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8036:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8037:                        /* 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)]); */
                   8038:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8039:                      }else{ /* Vn is dummy and Vm is quanti */
                   8040:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8041:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8042:                      }
                   8043:                    }else{ /* Vn*Vm Vn is quanti */
                   8044:                      if(DummyV[Tvard[ijp][2]]==0){
                   8045:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8046:                      }else{ /* Both quanti */
                   8047:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8048:                      }
1.237     brouard  8049:                    }
1.268     brouard  8050:                    ijp++;
1.237     brouard  8051:                  }
1.268     brouard  8052:                } /* end Tprod */
1.237     brouard  8053:              } else{  /* simple covariate */
1.264     brouard  8054:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8055:                if(Dummy[j]==0){
                   8056:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8057:                }else{ /* quantitative */
                   8058:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8059:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8060:                }
1.237     brouard  8061:              } /* end simple */
                   8062:            } /* end j */
1.223     brouard  8063:          }else{
                   8064:            i=i-ncovmodel;
                   8065:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8066:              fprintf(ficgp," (1.");
                   8067:          }
1.227     brouard  8068:          
1.223     brouard  8069:          if(ng != 1){
                   8070:            fprintf(ficgp,")/(1");
1.227     brouard  8071:            
1.264     brouard  8072:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8073:              if(nagesqr==0)
1.264     brouard  8074:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8075:              else /* nagesqr =1 */
1.264     brouard  8076:                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  8077:               
1.223     brouard  8078:              ij=1;
                   8079:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8080:                 if(cptcovage >0){ 
                   8081:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8082:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8083:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8084:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8085:                       ij++;
                   8086:                     }
                   8087:                   }
                   8088:                 }else
                   8089:                   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  8090:              }
                   8091:              fprintf(ficgp,")");
                   8092:            }
                   8093:            fprintf(ficgp,")");
                   8094:            if(ng ==2)
1.276     brouard  8095:              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  8096:            else /* ng= 3 */
1.276     brouard  8097:              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  8098:          }else{ /* end ng <> 1 */
                   8099:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8100:              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  8101:          }
                   8102:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8103:            fprintf(ficgp,",");
                   8104:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8105:            fprintf(ficgp,",");
                   8106:          i=i+ncovmodel;
                   8107:        } /* end k */
                   8108:       } /* end k2 */
1.276     brouard  8109:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8110:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8111:     } /* end k1 */
1.223     brouard  8112:   } /* end ng */
                   8113:   /* avoid: */
                   8114:   fflush(ficgp); 
1.126     brouard  8115: }  /* end gnuplot */
                   8116: 
                   8117: 
                   8118: /*************** Moving average **************/
1.219     brouard  8119: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8120:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8121:    
1.222     brouard  8122:    int i, cpt, cptcod;
                   8123:    int modcovmax =1;
                   8124:    int mobilavrange, mob;
                   8125:    int iage=0;
1.288     brouard  8126:    int firstA1=0, firstA2=0;
1.222     brouard  8127: 
1.266     brouard  8128:    double sum=0., sumr=0.;
1.222     brouard  8129:    double age;
1.266     brouard  8130:    double *sumnewp, *sumnewm, *sumnewmr;
                   8131:    double *agemingood, *agemaxgood; 
                   8132:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8133:   
                   8134:   
1.278     brouard  8135:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8136:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8137: 
                   8138:    sumnewp = vector(1,ncovcombmax);
                   8139:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8140:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8141:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8142:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8143:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8144:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8145: 
                   8146:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8147:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8148:      sumnewp[cptcod]=0.;
1.266     brouard  8149:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8150:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8151:    }
                   8152:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8153:   
1.266     brouard  8154:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8155:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8156:      else mobilavrange=mobilav;
                   8157:      for (age=bage; age<=fage; age++)
                   8158:        for (i=1; i<=nlstate;i++)
                   8159:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8160:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8161:      /* We keep the original values on the extreme ages bage, fage and for 
                   8162:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8163:        we use a 5 terms etc. until the borders are no more concerned. 
                   8164:      */ 
                   8165:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8166:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8167:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8168:           sumnewm[cptcod]=0.;
                   8169:           for (i=1; i<=nlstate;i++){
1.222     brouard  8170:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8171:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8172:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8173:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8174:             }
                   8175:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8176:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8177:           } /* end i */
                   8178:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8179:         } /* end cptcod */
1.222     brouard  8180:        }/* end age */
                   8181:      }/* end mob */
1.266     brouard  8182:    }else{
                   8183:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8184:      return -1;
1.266     brouard  8185:    }
                   8186: 
                   8187:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8188:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8189:      if(invalidvarcomb[cptcod]){
                   8190:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8191:        continue;
                   8192:      }
1.219     brouard  8193: 
1.266     brouard  8194:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8195:        sumnewm[cptcod]=0.;
                   8196:        sumnewmr[cptcod]=0.;
                   8197:        for (i=1; i<=nlstate;i++){
                   8198:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8199:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8200:        }
                   8201:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8202:         agemingoodr[cptcod]=age;
                   8203:        }
                   8204:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8205:           agemingood[cptcod]=age;
                   8206:        }
                   8207:      } /* age */
                   8208:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8209:        sumnewm[cptcod]=0.;
1.266     brouard  8210:        sumnewmr[cptcod]=0.;
1.222     brouard  8211:        for (i=1; i<=nlstate;i++){
                   8212:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8213:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8214:        }
                   8215:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8216:         agemaxgoodr[cptcod]=age;
1.222     brouard  8217:        }
                   8218:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8219:         agemaxgood[cptcod]=age;
                   8220:        }
                   8221:      } /* age */
                   8222:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8223:      /* but they will change */
1.288     brouard  8224:      firstA1=0;firstA2=0;
1.266     brouard  8225:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8226:        sumnewm[cptcod]=0.;
                   8227:        sumnewmr[cptcod]=0.;
                   8228:        for (i=1; i<=nlstate;i++){
                   8229:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8230:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8231:        }
                   8232:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8233:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8234:           agemaxgoodr[cptcod]=age;  /* age min */
                   8235:           for (i=1; i<=nlstate;i++)
                   8236:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8237:         }else{ /* bad we change the value with the values of good ages */
                   8238:           for (i=1; i<=nlstate;i++){
                   8239:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8240:           } /* i */
                   8241:         } /* end bad */
                   8242:        }else{
                   8243:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8244:           agemaxgood[cptcod]=age;
                   8245:         }else{ /* bad we change the value with the values of good ages */
                   8246:           for (i=1; i<=nlstate;i++){
                   8247:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8248:           } /* i */
                   8249:         } /* end bad */
                   8250:        }/* end else */
                   8251:        sum=0.;sumr=0.;
                   8252:        for (i=1; i<=nlstate;i++){
                   8253:         sum+=mobaverage[(int)age][i][cptcod];
                   8254:         sumr+=probs[(int)age][i][cptcod];
                   8255:        }
                   8256:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8257:         if(!firstA1){
                   8258:           firstA1=1;
                   8259:           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);
                   8260:         }
                   8261:         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  8262:        } /* end bad */
                   8263:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8264:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8265:         if(!firstA2){
                   8266:           firstA2=1;
                   8267:           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);
                   8268:         }
                   8269:         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  8270:        } /* end bad */
                   8271:      }/* age */
1.266     brouard  8272: 
                   8273:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8274:        sumnewm[cptcod]=0.;
1.266     brouard  8275:        sumnewmr[cptcod]=0.;
1.222     brouard  8276:        for (i=1; i<=nlstate;i++){
                   8277:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8278:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8279:        } 
                   8280:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8281:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8282:           agemingoodr[cptcod]=age;
                   8283:           for (i=1; i<=nlstate;i++)
                   8284:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8285:         }else{ /* bad we change the value with the values of good ages */
                   8286:           for (i=1; i<=nlstate;i++){
                   8287:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8288:           } /* i */
                   8289:         } /* end bad */
                   8290:        }else{
                   8291:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8292:           agemingood[cptcod]=age;
                   8293:         }else{ /* bad */
                   8294:           for (i=1; i<=nlstate;i++){
                   8295:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8296:           } /* i */
                   8297:         } /* end bad */
                   8298:        }/* end else */
                   8299:        sum=0.;sumr=0.;
                   8300:        for (i=1; i<=nlstate;i++){
                   8301:         sum+=mobaverage[(int)age][i][cptcod];
                   8302:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8303:        }
1.266     brouard  8304:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8305:         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  8306:        } /* end bad */
                   8307:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8308:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8309:         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  8310:        } /* end bad */
                   8311:      }/* age */
1.266     brouard  8312: 
1.222     brouard  8313:                
                   8314:      for (age=bage; age<=fage; age++){
1.235     brouard  8315:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8316:        sumnewp[cptcod]=0.;
                   8317:        sumnewm[cptcod]=0.;
                   8318:        for (i=1; i<=nlstate;i++){
                   8319:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8320:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8321:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8322:        }
                   8323:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8324:      }
                   8325:      /* printf("\n"); */
                   8326:      /* } */
1.266     brouard  8327: 
1.222     brouard  8328:      /* brutal averaging */
1.266     brouard  8329:      /* for (i=1; i<=nlstate;i++){ */
                   8330:      /*   for (age=1; age<=bage; age++){ */
                   8331:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8332:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8333:      /*   }     */
                   8334:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8335:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8336:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8337:      /*   } */
                   8338:      /* } /\* end i status *\/ */
                   8339:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8340:      /*   for (age=1; age<=AGESUP; age++){ */
                   8341:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8342:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8343:      /*   } */
                   8344:      /* } */
1.222     brouard  8345:    }/* end cptcod */
1.266     brouard  8346:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8347:    free_vector(agemaxgood,1, ncovcombmax);
                   8348:    free_vector(agemingood,1, ncovcombmax);
                   8349:    free_vector(agemingoodr,1, ncovcombmax);
                   8350:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8351:    free_vector(sumnewm,1, ncovcombmax);
                   8352:    free_vector(sumnewp,1, ncovcombmax);
                   8353:    return 0;
                   8354:  }/* End movingaverage */
1.218     brouard  8355:  
1.126     brouard  8356: 
1.296     brouard  8357:  
1.126     brouard  8358: /************** Forecasting ******************/
1.296     brouard  8359: /* 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)*/
                   8360: 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){
                   8361:   /* dateintemean, mean date of interviews
                   8362:      dateprojd, year, month, day of starting projection 
                   8363:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8364:      agemin, agemax range of age
                   8365:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8366:   */
1.296     brouard  8367:   /* double anprojd, mprojd, jprojd; */
                   8368:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8369:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8370:   double agec; /* generic age */
1.296     brouard  8371:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8372:   double *popeffectif,*popcount;
                   8373:   double ***p3mat;
1.218     brouard  8374:   /* double ***mobaverage; */
1.126     brouard  8375:   char fileresf[FILENAMELENGTH];
                   8376: 
                   8377:   agelim=AGESUP;
1.211     brouard  8378:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8379:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8380:      We still use firstpass and lastpass as another selection.
                   8381:   */
1.214     brouard  8382:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8383:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8384:  
1.201     brouard  8385:   strcpy(fileresf,"F_"); 
                   8386:   strcat(fileresf,fileresu);
1.126     brouard  8387:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8388:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8389:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8390:   }
1.235     brouard  8391:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8392:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8393: 
1.225     brouard  8394:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8395: 
                   8396: 
                   8397:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8398:   if (stepm<=12) stepsize=1;
                   8399:   if(estepm < stepm){
                   8400:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8401:   }
1.270     brouard  8402:   else{
                   8403:     hstepm=estepm;   
                   8404:   }
                   8405:   if(estepm > stepm){ /* Yes every two year */
                   8406:     stepsize=2;
                   8407:   }
1.296     brouard  8408:   hstepm=hstepm/stepm;
1.126     brouard  8409: 
1.296     brouard  8410:   
                   8411:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8412:   /*                              fractional in yp1 *\/ */
                   8413:   /* aintmean=yp; */
                   8414:   /* yp2=modf((yp1*12),&yp); */
                   8415:   /* mintmean=yp; */
                   8416:   /* yp1=modf((yp2*30.5),&yp); */
                   8417:   /* jintmean=yp; */
                   8418:   /* if(jintmean==0) jintmean=1; */
                   8419:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8420: 
1.296     brouard  8421: 
                   8422:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8423:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8424:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8425:   i1=pow(2,cptcoveff);
1.126     brouard  8426:   if (cptcovn < 1){i1=1;}
                   8427:   
1.296     brouard  8428:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8429:   
                   8430:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8431:   
1.126     brouard  8432: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8433:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8434:   for(k=1; k<=i1;k++){
1.253     brouard  8435:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8436:       continue;
1.227     brouard  8437:     if(invalidvarcomb[k]){
                   8438:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8439:       continue;
                   8440:     }
                   8441:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8442:     for(j=1;j<=cptcoveff;j++) {
                   8443:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8444:     }
1.235     brouard  8445:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8446:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8447:     }
1.227     brouard  8448:     fprintf(ficresf," yearproj age");
                   8449:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8450:       for(i=1; i<=nlstate;i++)               
                   8451:        fprintf(ficresf," p%d%d",i,j);
                   8452:       fprintf(ficresf," wp.%d",j);
                   8453:     }
1.296     brouard  8454:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8455:       fprintf(ficresf,"\n");
1.296     brouard  8456:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8457:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8458:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8459:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8460:        nhstepm = nhstepm/hstepm; 
                   8461:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8462:        oldm=oldms;savm=savms;
1.268     brouard  8463:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8464:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8465:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8466:        for (h=0; h<=nhstepm; h++){
                   8467:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8468:            break;
                   8469:          }
                   8470:        }
                   8471:        fprintf(ficresf,"\n");
                   8472:        for(j=1;j<=cptcoveff;j++) 
                   8473:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8474:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8475:        
                   8476:        for(j=1; j<=nlstate+ndeath;j++) {
                   8477:          ppij=0.;
                   8478:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8479:            if (mobilav>=1)
                   8480:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8481:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8482:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8483:            }
1.268     brouard  8484:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8485:          } /* end i */
                   8486:          fprintf(ficresf," %.3f", ppij);
                   8487:        }/* end j */
1.227     brouard  8488:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8489:       } /* end agec */
1.266     brouard  8490:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8491:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8492:     } /* end yearp */
                   8493:   } /* end  k */
1.219     brouard  8494:        
1.126     brouard  8495:   fclose(ficresf);
1.215     brouard  8496:   printf("End of Computing forecasting \n");
                   8497:   fprintf(ficlog,"End of Computing forecasting\n");
                   8498: 
1.126     brouard  8499: }
                   8500: 
1.269     brouard  8501: /************** Back Forecasting ******************/
1.296     brouard  8502:  /* 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){ */
                   8503:  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){
                   8504:   /* back1, year, month, day of starting backprojection
1.267     brouard  8505:      agemin, agemax range of age
                   8506:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8507:      anback2 year of end of backprojection (same day and month as back1).
                   8508:      prevacurrent and prev are prevalences.
1.267     brouard  8509:   */
                   8510:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8511:   double agec; /* generic age */
1.302     brouard  8512:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8513:   double *popeffectif,*popcount;
                   8514:   double ***p3mat;
                   8515:   /* double ***mobaverage; */
                   8516:   char fileresfb[FILENAMELENGTH];
                   8517:  
1.268     brouard  8518:   agelim=AGEINF;
1.267     brouard  8519:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8520:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8521:      We still use firstpass and lastpass as another selection.
                   8522:   */
                   8523:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8524:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8525: 
                   8526:   /*Do we need to compute prevalence again?*/
                   8527: 
                   8528:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8529:   
                   8530:   strcpy(fileresfb,"FB_");
                   8531:   strcat(fileresfb,fileresu);
                   8532:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8533:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8534:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8535:   }
                   8536:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8537:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8538:   
                   8539:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8540:   
                   8541:    
                   8542:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8543:   if (stepm<=12) stepsize=1;
                   8544:   if(estepm < stepm){
                   8545:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8546:   }
1.270     brouard  8547:   else{
                   8548:     hstepm=estepm;   
                   8549:   }
                   8550:   if(estepm >= stepm){ /* Yes every two year */
                   8551:     stepsize=2;
                   8552:   }
1.267     brouard  8553:   
                   8554:   hstepm=hstepm/stepm;
1.296     brouard  8555:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8556:   /*                              fractional in yp1 *\/ */
                   8557:   /* aintmean=yp; */
                   8558:   /* yp2=modf((yp1*12),&yp); */
                   8559:   /* mintmean=yp; */
                   8560:   /* yp1=modf((yp2*30.5),&yp); */
                   8561:   /* jintmean=yp; */
                   8562:   /* if(jintmean==0) jintmean=1; */
                   8563:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8564:   
                   8565:   i1=pow(2,cptcoveff);
                   8566:   if (cptcovn < 1){i1=1;}
                   8567:   
1.296     brouard  8568:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8569:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8570:   
                   8571:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8572:   
                   8573:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8574:   for(k=1; k<=i1;k++){
                   8575:     if(i1 != 1 && TKresult[nres]!= k)
                   8576:       continue;
                   8577:     if(invalidvarcomb[k]){
                   8578:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8579:       continue;
                   8580:     }
1.268     brouard  8581:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8582:     for(j=1;j<=cptcoveff;j++) {
                   8583:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8584:     }
                   8585:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8586:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8587:     }
                   8588:     fprintf(ficresfb," yearbproj age");
                   8589:     for(j=1; j<=nlstate+ndeath;j++){
                   8590:       for(i=1; i<=nlstate;i++)
1.268     brouard  8591:        fprintf(ficresfb," b%d%d",i,j);
                   8592:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8593:     }
1.296     brouard  8594:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8595:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8596:       fprintf(ficresfb,"\n");
1.296     brouard  8597:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8598:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8599:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8600:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8601:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8602:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8603:        nhstepm = nhstepm/hstepm;
                   8604:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8605:        oldm=oldms;savm=savms;
1.268     brouard  8606:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8607:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8608:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8609:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8610:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8611:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8612:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8613:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8614:            break;
                   8615:          }
                   8616:        }
                   8617:        fprintf(ficresfb,"\n");
                   8618:        for(j=1;j<=cptcoveff;j++)
                   8619:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8620:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8621:        for(i=1; i<=nlstate+ndeath;i++) {
                   8622:          ppij=0.;ppi=0.;
                   8623:          for(j=1; j<=nlstate;j++) {
                   8624:            /* if (mobilav==1) */
1.269     brouard  8625:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8626:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8627:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8628:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8629:              /* else { */
                   8630:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8631:              /* } */
1.268     brouard  8632:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8633:          } /* end j */
                   8634:          if(ppi <0.99){
                   8635:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8636:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8637:          }
                   8638:          fprintf(ficresfb," %.3f", ppij);
                   8639:        }/* end j */
1.267     brouard  8640:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8641:       } /* end agec */
                   8642:     } /* end yearp */
                   8643:   } /* end k */
1.217     brouard  8644:   
1.267     brouard  8645:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8646:   
1.267     brouard  8647:   fclose(ficresfb);
                   8648:   printf("End of Computing Back forecasting \n");
                   8649:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8650:        
1.267     brouard  8651: }
1.217     brouard  8652: 
1.269     brouard  8653: /* Variance of prevalence limit: varprlim */
                   8654:  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  8655:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8656:  
                   8657:    char fileresvpl[FILENAMELENGTH];  
                   8658:    FILE *ficresvpl;
                   8659:    double **oldm, **savm;
                   8660:    double **varpl; /* Variances of prevalence limits by age */   
                   8661:    int i1, k, nres, j ;
                   8662:    
                   8663:     strcpy(fileresvpl,"VPL_");
                   8664:     strcat(fileresvpl,fileresu);
                   8665:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8666:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8667:       exit(0);
                   8668:     }
1.288     brouard  8669:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8670:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8671:     
                   8672:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8673:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8674:     
                   8675:     i1=pow(2,cptcoveff);
                   8676:     if (cptcovn < 1){i1=1;}
                   8677: 
                   8678:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8679:     for(k=1; k<=i1;k++){
                   8680:       if(i1 != 1 && TKresult[nres]!= k)
                   8681:        continue;
                   8682:       fprintf(ficresvpl,"\n#****** ");
                   8683:       printf("\n#****** ");
                   8684:       fprintf(ficlog,"\n#****** ");
                   8685:       for(j=1;j<=cptcoveff;j++) {
                   8686:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8687:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8688:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8689:       }
                   8690:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8691:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8692:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8693:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8694:       }        
                   8695:       fprintf(ficresvpl,"******\n");
                   8696:       printf("******\n");
                   8697:       fprintf(ficlog,"******\n");
                   8698:       
                   8699:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8700:       oldm=oldms;savm=savms;
                   8701:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8702:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8703:       /*}*/
                   8704:     }
                   8705:     
                   8706:     fclose(ficresvpl);
1.288     brouard  8707:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8708:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8709: 
                   8710:  }
                   8711: /* Variance of back prevalence: varbprlim */
                   8712:  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){
                   8713:       /*------- Variance of back (stable) prevalence------*/
                   8714: 
                   8715:    char fileresvbl[FILENAMELENGTH];  
                   8716:    FILE  *ficresvbl;
                   8717: 
                   8718:    double **oldm, **savm;
                   8719:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8720:    int i1, k, nres, j ;
                   8721: 
                   8722:    strcpy(fileresvbl,"VBL_");
                   8723:    strcat(fileresvbl,fileresu);
                   8724:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8725:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8726:      exit(0);
                   8727:    }
                   8728:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8729:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8730:    
                   8731:    
                   8732:    i1=pow(2,cptcoveff);
                   8733:    if (cptcovn < 1){i1=1;}
                   8734:    
                   8735:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8736:      for(k=1; k<=i1;k++){
                   8737:        if(i1 != 1 && TKresult[nres]!= k)
                   8738:         continue;
                   8739:        fprintf(ficresvbl,"\n#****** ");
                   8740:        printf("\n#****** ");
                   8741:        fprintf(ficlog,"\n#****** ");
                   8742:        for(j=1;j<=cptcoveff;j++) {
                   8743:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8744:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8745:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8746:        }
                   8747:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8748:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8749:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8750:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8751:        }
                   8752:        fprintf(ficresvbl,"******\n");
                   8753:        printf("******\n");
                   8754:        fprintf(ficlog,"******\n");
                   8755:        
                   8756:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8757:        oldm=oldms;savm=savms;
                   8758:        
                   8759:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8760:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8761:        /*}*/
                   8762:      }
                   8763:    
                   8764:    fclose(ficresvbl);
                   8765:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8766:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8767: 
                   8768:  } /* End of varbprlim */
                   8769: 
1.126     brouard  8770: /************** Forecasting *****not tested NB*************/
1.227     brouard  8771: /* 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  8772:   
1.227     brouard  8773: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8774: /*   int *popage; */
                   8775: /*   double calagedatem, agelim, kk1, kk2; */
                   8776: /*   double *popeffectif,*popcount; */
                   8777: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8778: /*   /\* double ***mobaverage; *\/ */
                   8779: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8780: 
1.227     brouard  8781: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8782: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8783: /*   agelim=AGESUP; */
                   8784: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8785:   
1.227     brouard  8786: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8787:   
                   8788:   
1.227     brouard  8789: /*   strcpy(filerespop,"POP_");  */
                   8790: /*   strcat(filerespop,fileresu); */
                   8791: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8792: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8793: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8794: /*   } */
                   8795: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8796: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8797: 
1.227     brouard  8798: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8799: 
1.227     brouard  8800: /*   /\* if (mobilav!=0) { *\/ */
                   8801: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8802: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8803: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8804: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8805: /*   /\*   } *\/ */
                   8806: /*   /\* } *\/ */
1.126     brouard  8807: 
1.227     brouard  8808: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8809: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8810:   
1.227     brouard  8811: /*   agelim=AGESUP; */
1.126     brouard  8812:   
1.227     brouard  8813: /*   hstepm=1; */
                   8814: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8815:        
1.227     brouard  8816: /*   if (popforecast==1) { */
                   8817: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8818: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8819: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8820: /*     }  */
                   8821: /*     popage=ivector(0,AGESUP); */
                   8822: /*     popeffectif=vector(0,AGESUP); */
                   8823: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8824:     
1.227     brouard  8825: /*     i=1;    */
                   8826: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8827:     
1.227     brouard  8828: /*     imx=i; */
                   8829: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8830: /*   } */
1.218     brouard  8831:   
1.227     brouard  8832: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8833: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8834: /*       k=k+1; */
                   8835: /*       fprintf(ficrespop,"\n#******"); */
                   8836: /*       for(j=1;j<=cptcoveff;j++) { */
                   8837: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8838: /*       } */
                   8839: /*       fprintf(ficrespop,"******\n"); */
                   8840: /*       fprintf(ficrespop,"# Age"); */
                   8841: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8842: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8843:       
1.227     brouard  8844: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8845: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8846:        
1.227     brouard  8847: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8848: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8849: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8850:          
1.227     brouard  8851: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8852: /*       oldm=oldms;savm=savms; */
                   8853: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8854:          
1.227     brouard  8855: /*       for (h=0; h<=nhstepm; h++){ */
                   8856: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8857: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8858: /*         }  */
                   8859: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8860: /*           kk1=0.;kk2=0; */
                   8861: /*           for(i=1; i<=nlstate;i++) {               */
                   8862: /*             if (mobilav==1)  */
                   8863: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8864: /*             else { */
                   8865: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8866: /*             } */
                   8867: /*           } */
                   8868: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8869: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8870: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8871: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8872: /*           } */
                   8873: /*         } */
                   8874: /*         for(i=1; i<=nlstate;i++){ */
                   8875: /*           kk1=0.; */
                   8876: /*           for(j=1; j<=nlstate;j++){ */
                   8877: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8878: /*           } */
                   8879: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8880: /*         } */
1.218     brouard  8881:            
1.227     brouard  8882: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8883: /*           for(j=1; j<=nlstate;j++)  */
                   8884: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8885: /*       } */
                   8886: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8887: /*     } */
                   8888: /*       } */
1.218     brouard  8889:       
1.227     brouard  8890: /*       /\******\/ */
1.218     brouard  8891:       
1.227     brouard  8892: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8893: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8894: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8895: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8896: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8897:          
1.227     brouard  8898: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8899: /*       oldm=oldms;savm=savms; */
                   8900: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8901: /*       for (h=0; h<=nhstepm; h++){ */
                   8902: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8903: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8904: /*         }  */
                   8905: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8906: /*           kk1=0.;kk2=0; */
                   8907: /*           for(i=1; i<=nlstate;i++) {               */
                   8908: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8909: /*           } */
                   8910: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8911: /*         } */
                   8912: /*       } */
                   8913: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8914: /*     } */
                   8915: /*       } */
                   8916: /*     }  */
                   8917: /*   } */
1.218     brouard  8918:   
1.227     brouard  8919: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  8920:   
1.227     brouard  8921: /*   if (popforecast==1) { */
                   8922: /*     free_ivector(popage,0,AGESUP); */
                   8923: /*     free_vector(popeffectif,0,AGESUP); */
                   8924: /*     free_vector(popcount,0,AGESUP); */
                   8925: /*   } */
                   8926: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8927: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8928: /*   fclose(ficrespop); */
                   8929: /* } /\* End of popforecast *\/ */
1.218     brouard  8930:  
1.126     brouard  8931: int fileappend(FILE *fichier, char *optionfich)
                   8932: {
                   8933:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   8934:     printf("Problem with file: %s\n", optionfich);
                   8935:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   8936:     return (0);
                   8937:   }
                   8938:   fflush(fichier);
                   8939:   return (1);
                   8940: }
                   8941: 
                   8942: 
                   8943: /**************** function prwizard **********************/
                   8944: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   8945: {
                   8946: 
                   8947:   /* Wizard to print covariance matrix template */
                   8948: 
1.164     brouard  8949:   char ca[32], cb[32];
                   8950:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  8951:   int numlinepar;
                   8952: 
                   8953:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8954:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8955:   for(i=1; i <=nlstate; i++){
                   8956:     jj=0;
                   8957:     for(j=1; j <=nlstate+ndeath; j++){
                   8958:       if(j==i) continue;
                   8959:       jj++;
                   8960:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   8961:       printf("%1d%1d",i,j);
                   8962:       fprintf(ficparo,"%1d%1d",i,j);
                   8963:       for(k=1; k<=ncovmodel;k++){
                   8964:        /*        printf(" %lf",param[i][j][k]); */
                   8965:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   8966:        printf(" 0.");
                   8967:        fprintf(ficparo," 0.");
                   8968:       }
                   8969:       printf("\n");
                   8970:       fprintf(ficparo,"\n");
                   8971:     }
                   8972:   }
                   8973:   printf("# Scales (for hessian or gradient estimation)\n");
                   8974:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   8975:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   8976:   for(i=1; i <=nlstate; i++){
                   8977:     jj=0;
                   8978:     for(j=1; j <=nlstate+ndeath; j++){
                   8979:       if(j==i) continue;
                   8980:       jj++;
                   8981:       fprintf(ficparo,"%1d%1d",i,j);
                   8982:       printf("%1d%1d",i,j);
                   8983:       fflush(stdout);
                   8984:       for(k=1; k<=ncovmodel;k++){
                   8985:        /*      printf(" %le",delti3[i][j][k]); */
                   8986:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   8987:        printf(" 0.");
                   8988:        fprintf(ficparo," 0.");
                   8989:       }
                   8990:       numlinepar++;
                   8991:       printf("\n");
                   8992:       fprintf(ficparo,"\n");
                   8993:     }
                   8994:   }
                   8995:   printf("# Covariance matrix\n");
                   8996: /* # 121 Var(a12)\n\ */
                   8997: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8998: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8999: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9000: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9001: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9002: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9003: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9004:   fflush(stdout);
                   9005:   fprintf(ficparo,"# Covariance matrix\n");
                   9006:   /* # 121 Var(a12)\n\ */
                   9007:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9008:   /* #   ...\n\ */
                   9009:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9010:   
                   9011:   for(itimes=1;itimes<=2;itimes++){
                   9012:     jj=0;
                   9013:     for(i=1; i <=nlstate; i++){
                   9014:       for(j=1; j <=nlstate+ndeath; j++){
                   9015:        if(j==i) continue;
                   9016:        for(k=1; k<=ncovmodel;k++){
                   9017:          jj++;
                   9018:          ca[0]= k+'a'-1;ca[1]='\0';
                   9019:          if(itimes==1){
                   9020:            printf("#%1d%1d%d",i,j,k);
                   9021:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9022:          }else{
                   9023:            printf("%1d%1d%d",i,j,k);
                   9024:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9025:            /*  printf(" %.5le",matcov[i][j]); */
                   9026:          }
                   9027:          ll=0;
                   9028:          for(li=1;li <=nlstate; li++){
                   9029:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9030:              if(lj==li) continue;
                   9031:              for(lk=1;lk<=ncovmodel;lk++){
                   9032:                ll++;
                   9033:                if(ll<=jj){
                   9034:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9035:                  if(ll<jj){
                   9036:                    if(itimes==1){
                   9037:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9038:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9039:                    }else{
                   9040:                      printf(" 0.");
                   9041:                      fprintf(ficparo," 0.");
                   9042:                    }
                   9043:                  }else{
                   9044:                    if(itimes==1){
                   9045:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9046:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9047:                    }else{
                   9048:                      printf(" 0.");
                   9049:                      fprintf(ficparo," 0.");
                   9050:                    }
                   9051:                  }
                   9052:                }
                   9053:              } /* end lk */
                   9054:            } /* end lj */
                   9055:          } /* end li */
                   9056:          printf("\n");
                   9057:          fprintf(ficparo,"\n");
                   9058:          numlinepar++;
                   9059:        } /* end k*/
                   9060:       } /*end j */
                   9061:     } /* end i */
                   9062:   } /* end itimes */
                   9063: 
                   9064: } /* end of prwizard */
                   9065: /******************* Gompertz Likelihood ******************************/
                   9066: double gompertz(double x[])
                   9067: { 
1.302     brouard  9068:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9069:   int i,n=0; /* n is the size of the sample */
                   9070: 
1.220     brouard  9071:   for (i=1;i<=imx ; i++) {
1.126     brouard  9072:     sump=sump+weight[i];
                   9073:     /*    sump=sump+1;*/
                   9074:     num=num+1;
                   9075:   }
1.302     brouard  9076:   L=0.0;
                   9077:   /* agegomp=AGEGOMP; */
1.126     brouard  9078:   /* for (i=0; i<=imx; i++) 
                   9079:      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]);*/
                   9080: 
1.302     brouard  9081:   for (i=1;i<=imx ; i++) {
                   9082:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9083:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9084:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9085:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9086:      * +
                   9087:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9088:      */
                   9089:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9090:        if (cens[i] == 1){
                   9091:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9092:        } else if (cens[i] == 0){
1.126     brouard  9093:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9094:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9095:       } else
                   9096:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9097:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9098:        L=L+A*weight[i];
1.126     brouard  9099:        /*      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  9100:      }
                   9101:   }
1.126     brouard  9102: 
1.302     brouard  9103:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9104:  
                   9105:   return -2*L*num/sump;
                   9106: }
                   9107: 
1.136     brouard  9108: #ifdef GSL
                   9109: /******************* Gompertz_f Likelihood ******************************/
                   9110: double gompertz_f(const gsl_vector *v, void *params)
                   9111: { 
1.302     brouard  9112:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9113:   double *x= (double *) v->data;
                   9114:   int i,n=0; /* n is the size of the sample */
                   9115: 
                   9116:   for (i=0;i<=imx-1 ; i++) {
                   9117:     sump=sump+weight[i];
                   9118:     /*    sump=sump+1;*/
                   9119:     num=num+1;
                   9120:   }
                   9121:  
                   9122:  
                   9123:   /* for (i=0; i<=imx; i++) 
                   9124:      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]);*/
                   9125:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9126:   for (i=1;i<=imx ; i++)
                   9127:     {
                   9128:       if (cens[i] == 1 && wav[i]>1)
                   9129:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9130:       
                   9131:       if (cens[i] == 0 && wav[i]>1)
                   9132:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9133:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9134:       
                   9135:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9136:       if (wav[i] > 1 ) { /* ??? */
                   9137:        LL=LL+A*weight[i];
                   9138:        /*      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]);*/
                   9139:       }
                   9140:     }
                   9141: 
                   9142:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9143:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9144:  
                   9145:   return -2*LL*num/sump;
                   9146: }
                   9147: #endif
                   9148: 
1.126     brouard  9149: /******************* Printing html file ***********/
1.201     brouard  9150: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9151:                  int lastpass, int stepm, int weightopt, char model[],\
                   9152:                  int imx,  double p[],double **matcov,double agemortsup){
                   9153:   int i,k;
                   9154: 
                   9155:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9156:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9157:   for (i=1;i<=2;i++) 
                   9158:     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  9159:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9160:   fprintf(fichtm,"</ul>");
                   9161: 
                   9162: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9163: 
                   9164:  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>");
                   9165: 
                   9166:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9167:    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]);
                   9168: 
                   9169:  
                   9170:   fflush(fichtm);
                   9171: }
                   9172: 
                   9173: /******************* Gnuplot file **************/
1.201     brouard  9174: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9175: 
                   9176:   char dirfileres[132],optfileres[132];
1.164     brouard  9177: 
1.126     brouard  9178:   int ng;
                   9179: 
                   9180: 
                   9181:   /*#ifdef windows */
                   9182:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9183:     /*#endif */
                   9184: 
                   9185: 
                   9186:   strcpy(dirfileres,optionfilefiname);
                   9187:   strcpy(optfileres,"vpl");
1.199     brouard  9188:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9189:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9190:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9191:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9192:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9193: 
                   9194: } 
                   9195: 
1.136     brouard  9196: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9197: {
1.126     brouard  9198: 
1.136     brouard  9199:   /*-------- data file ----------*/
                   9200:   FILE *fic;
                   9201:   char dummy[]="                         ";
1.240     brouard  9202:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9203:   int lstra;
1.136     brouard  9204:   int linei, month, year,iout;
1.302     brouard  9205:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9206:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9207:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9208:   char *stratrunc;
1.223     brouard  9209: 
1.240     brouard  9210:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9211:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9212: 
1.240     brouard  9213:   for(v=1; v <=ncovcol;v++){
                   9214:     DummyV[v]=0;
                   9215:     FixedV[v]=0;
                   9216:   }
                   9217:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9218:     DummyV[v]=1;
                   9219:     FixedV[v]=0;
                   9220:   }
                   9221:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9222:     DummyV[v]=0;
                   9223:     FixedV[v]=1;
                   9224:   }
                   9225:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9226:     DummyV[v]=1;
                   9227:     FixedV[v]=1;
                   9228:   }
                   9229:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9230:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9231:     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]);
                   9232:   }
1.126     brouard  9233: 
1.136     brouard  9234:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9235:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9236:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9237:   }
1.126     brouard  9238: 
1.302     brouard  9239:     /* Is it a BOM UTF-8 Windows file? */
                   9240:   /* First data line */
                   9241:   linei=0;
                   9242:   while(fgets(line, MAXLINE, fic)) {
                   9243:     noffset=0;
                   9244:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9245:     {
                   9246:       noffset=noffset+3;
                   9247:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9248:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9249:       fflush(ficlog); return 1;
                   9250:     }
                   9251:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9252:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9253:     {
                   9254:       noffset=noffset+2;
                   9255:       printf("# 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);
                   9256:       fprintf(ficlog,"# Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
                   9257:       fflush(ficlog); return 1;
                   9258:     }
                   9259:     else if( line[0] == 0 && line[1] == 0)
                   9260:     {
                   9261:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9262:        noffset=noffset+4;
                   9263:        printf("# 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);
                   9264:        fprintf(ficlog,"# Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
                   9265:        fflush(ficlog); return 1;
                   9266:       }
                   9267:     } else{
                   9268:       ;/*printf(" Not a BOM file\n");*/
                   9269:     }
                   9270:         /* If line starts with a # it is a comment */
                   9271:     if (line[noffset] == '#') {
                   9272:       linei=linei+1;
                   9273:       break;
                   9274:     }else{
                   9275:       break;
                   9276:     }
                   9277:   }
                   9278:   fclose(fic);
                   9279:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9280:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9281:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9282:   }
                   9283:   /* Not a Bom file */
                   9284:   
1.136     brouard  9285:   i=1;
                   9286:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9287:     linei=linei+1;
                   9288:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9289:       if(line[j] == '\t')
                   9290:        line[j] = ' ';
                   9291:     }
                   9292:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9293:       ;
                   9294:     };
                   9295:     line[j+1]=0;  /* Trims blanks at end of line */
                   9296:     if(line[0]=='#'){
                   9297:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9298:       printf("Comment line\n%s\n",line);
                   9299:       continue;
                   9300:     }
                   9301:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9302:     strcpy(line, linetmp);
1.223     brouard  9303:     
                   9304:     /* Loops on waves */
                   9305:     for (j=maxwav;j>=1;j--){
                   9306:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9307:        cutv(stra, strb, line, ' '); 
                   9308:        if(strb[0]=='.') { /* Missing value */
                   9309:          lval=-1;
                   9310:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9311:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9312:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9313:            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);
                   9314:            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);
                   9315:            return 1;
                   9316:          }
                   9317:        }else{
                   9318:          errno=0;
                   9319:          /* what_kind_of_number(strb); */
                   9320:          dval=strtod(strb,&endptr); 
                   9321:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9322:          /* if(strb != endptr && *endptr == '\0') */
                   9323:          /*    dval=dlval; */
                   9324:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9325:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9326:            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);
                   9327:            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);
                   9328:            return 1;
                   9329:          }
                   9330:          cotqvar[j][iv][i]=dval; 
                   9331:          cotvar[j][ntv+iv][i]=dval; 
                   9332:        }
                   9333:        strcpy(line,stra);
1.223     brouard  9334:       }/* end loop ntqv */
1.225     brouard  9335:       
1.223     brouard  9336:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9337:        cutv(stra, strb, line, ' '); 
                   9338:        if(strb[0]=='.') { /* Missing value */
                   9339:          lval=-1;
                   9340:        }else{
                   9341:          errno=0;
                   9342:          lval=strtol(strb,&endptr,10); 
                   9343:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9344:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9345:            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);
                   9346:            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);
                   9347:            return 1;
                   9348:          }
                   9349:        }
                   9350:        if(lval <-1 || lval >1){
                   9351:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9352:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9353:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9354:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9355:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9356:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9357:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9358:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9359:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9360:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9361:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9362:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9363:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9364:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9365:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9366:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9367:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9368:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9369:          return 1;
                   9370:        }
                   9371:        cotvar[j][iv][i]=(double)(lval);
                   9372:        strcpy(line,stra);
1.223     brouard  9373:       }/* end loop ntv */
1.225     brouard  9374:       
1.223     brouard  9375:       /* Statuses  at wave */
1.137     brouard  9376:       cutv(stra, strb, line, ' '); 
1.223     brouard  9377:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9378:        lval=-1;
1.136     brouard  9379:       }else{
1.238     brouard  9380:        errno=0;
                   9381:        lval=strtol(strb,&endptr,10); 
                   9382:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9383:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9384:          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);
                   9385:          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);
                   9386:          return 1;
                   9387:        }
1.136     brouard  9388:       }
1.225     brouard  9389:       
1.136     brouard  9390:       s[j][i]=lval;
1.225     brouard  9391:       
1.223     brouard  9392:       /* Date of Interview */
1.136     brouard  9393:       strcpy(line,stra);
                   9394:       cutv(stra, strb,line,' ');
1.169     brouard  9395:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9396:       }
1.169     brouard  9397:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9398:        month=99;
                   9399:        year=9999;
1.136     brouard  9400:       }else{
1.225     brouard  9401:        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);
                   9402:        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);
                   9403:        return 1;
1.136     brouard  9404:       }
                   9405:       anint[j][i]= (double) year; 
1.302     brouard  9406:       mint[j][i]= (double)month;
                   9407:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9408:       /*       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]); */
                   9409:       /*       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]); */
                   9410:       /* } */
1.136     brouard  9411:       strcpy(line,stra);
1.223     brouard  9412:     } /* End loop on waves */
1.225     brouard  9413:     
1.223     brouard  9414:     /* Date of death */
1.136     brouard  9415:     cutv(stra, strb,line,' '); 
1.169     brouard  9416:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9417:     }
1.169     brouard  9418:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9419:       month=99;
                   9420:       year=9999;
                   9421:     }else{
1.141     brouard  9422:       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  9423:       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);
                   9424:       return 1;
1.136     brouard  9425:     }
                   9426:     andc[i]=(double) year; 
                   9427:     moisdc[i]=(double) month; 
                   9428:     strcpy(line,stra);
                   9429:     
1.223     brouard  9430:     /* Date of birth */
1.136     brouard  9431:     cutv(stra, strb,line,' '); 
1.169     brouard  9432:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9433:     }
1.169     brouard  9434:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9435:       month=99;
                   9436:       year=9999;
                   9437:     }else{
1.141     brouard  9438:       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);
                   9439:       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  9440:       return 1;
1.136     brouard  9441:     }
                   9442:     if (year==9999) {
1.141     brouard  9443:       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);
                   9444:       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  9445:       return 1;
                   9446:       
1.136     brouard  9447:     }
                   9448:     annais[i]=(double)(year);
1.302     brouard  9449:     moisnais[i]=(double)(month);
                   9450:     for (j=1;j<=maxwav;j++){
                   9451:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9452:        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]);
                   9453:        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]);
                   9454:       }
                   9455:     }
                   9456: 
1.136     brouard  9457:     strcpy(line,stra);
1.225     brouard  9458:     
1.223     brouard  9459:     /* Sample weight */
1.136     brouard  9460:     cutv(stra, strb,line,' '); 
                   9461:     errno=0;
                   9462:     dval=strtod(strb,&endptr); 
                   9463:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9464:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9465:       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  9466:       fflush(ficlog);
                   9467:       return 1;
                   9468:     }
                   9469:     weight[i]=dval; 
                   9470:     strcpy(line,stra);
1.225     brouard  9471:     
1.223     brouard  9472:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9473:       cutv(stra, strb, line, ' '); 
                   9474:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9475:        lval=-1;
1.223     brouard  9476:       }else{
1.225     brouard  9477:        errno=0;
                   9478:        /* what_kind_of_number(strb); */
                   9479:        dval=strtod(strb,&endptr);
                   9480:        /* if(strb != endptr && *endptr == '\0') */
                   9481:        /*   dval=dlval; */
                   9482:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9483:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9484:          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);
                   9485:          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);
                   9486:          return 1;
                   9487:        }
                   9488:        coqvar[iv][i]=dval; 
1.226     brouard  9489:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9490:       }
                   9491:       strcpy(line,stra);
                   9492:     }/* end loop nqv */
1.136     brouard  9493:     
1.223     brouard  9494:     /* Covariate values */
1.136     brouard  9495:     for (j=ncovcol;j>=1;j--){
                   9496:       cutv(stra, strb,line,' '); 
1.223     brouard  9497:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9498:        lval=-1;
1.136     brouard  9499:       }else{
1.225     brouard  9500:        errno=0;
                   9501:        lval=strtol(strb,&endptr,10); 
                   9502:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9503:          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);
                   9504:          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);
                   9505:          return 1;
                   9506:        }
1.136     brouard  9507:       }
                   9508:       if(lval <-1 || lval >1){
1.225     brouard  9509:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9510:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9511:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9512:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9513:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9514:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9515:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9516:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9517:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9518:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9519:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9520:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9521:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9522:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9523:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9524:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9525:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9526:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9527:        return 1;
1.136     brouard  9528:       }
                   9529:       covar[j][i]=(double)(lval);
                   9530:       strcpy(line,stra);
                   9531:     }  
                   9532:     lstra=strlen(stra);
1.225     brouard  9533:     
1.136     brouard  9534:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9535:       stratrunc = &(stra[lstra-9]);
                   9536:       num[i]=atol(stratrunc);
                   9537:     }
                   9538:     else
                   9539:       num[i]=atol(stra);
                   9540:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9541:       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;}*/
                   9542:     
                   9543:     i=i+1;
                   9544:   } /* End loop reading  data */
1.225     brouard  9545:   
1.136     brouard  9546:   *imax=i-1; /* Number of individuals */
                   9547:   fclose(fic);
1.225     brouard  9548:   
1.136     brouard  9549:   return (0);
1.164     brouard  9550:   /* endread: */
1.225     brouard  9551:   printf("Exiting readdata: ");
                   9552:   fclose(fic);
                   9553:   return (1);
1.223     brouard  9554: }
1.126     brouard  9555: 
1.234     brouard  9556: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9557:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9558:   while (*p2 == ' ')
1.234     brouard  9559:     p2++; 
                   9560:   /* while ((*p1++ = *p2++) !=0) */
                   9561:   /*   ; */
                   9562:   /* do */
                   9563:   /*   while (*p2 == ' ') */
                   9564:   /*     p2++; */
                   9565:   /* while (*p1++ == *p2++); */
                   9566:   *stri=p2; 
1.145     brouard  9567: }
                   9568: 
1.235     brouard  9569: int decoderesult ( char resultline[], int nres)
1.230     brouard  9570: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9571: {
1.235     brouard  9572:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9573:   char resultsav[MAXLINE];
1.234     brouard  9574:   int resultmodel[MAXLINE];
                   9575:   int modelresult[MAXLINE];
1.230     brouard  9576:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9577: 
1.234     brouard  9578:   removefirstspace(&resultline);
1.233     brouard  9579:   printf("decoderesult:%s\n",resultline);
1.230     brouard  9580: 
                   9581:   if (strstr(resultline,"v") !=0){
                   9582:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9583:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9584:     return 1;
                   9585:   }
                   9586:   trimbb(resultsav, resultline);
                   9587:   if (strlen(resultsav) >1){
                   9588:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9589:   }
1.253     brouard  9590:   if(j == 0){ /* Resultline but no = */
                   9591:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9592:     return (0);
                   9593:   }
                   9594:     
1.234     brouard  9595:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   9596:     printf("ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   9597:     fprintf(ficlog,"ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   9598:   }
                   9599:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9600:     if(nbocc(resultsav,'=') >1){
                   9601:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   9602:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   9603:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9604:     }else
                   9605:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9606:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9607:     
1.230     brouard  9608:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9609:     Tvarsel[k]=atoi(strc);
                   9610:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9611:     /* cptcovsel++;     */
                   9612:     if (nbocc(stra,'=') >0)
                   9613:       strcpy(resultsav,stra); /* and analyzes it */
                   9614:   }
1.235     brouard  9615:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9616:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9617:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9618:       match=0;
1.236     brouard  9619:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9620:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9621:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9622:          match=1;
                   9623:          break;
                   9624:        }
                   9625:       }
                   9626:       if(match == 0){
                   9627:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9628:       }
                   9629:     }
                   9630:   }
1.235     brouard  9631:   /* Checking for missing or useless values in comparison of current model needs */
                   9632:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9633:     match=0;
1.235     brouard  9634:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9635:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9636:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9637:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9638:          ++match;
                   9639:        }
                   9640:       }
                   9641:     }
                   9642:     if(match == 0){
                   9643:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9644:     }else if(match > 1){
                   9645:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9646:     }
                   9647:   }
1.235     brouard  9648:       
1.234     brouard  9649:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9650:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9651:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9652:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9653:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9654:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9655:   /*    1 0 0 0 */
                   9656:   /*    2 1 0 0 */
                   9657:   /*    3 0 1 0 */ 
                   9658:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9659:   /*    5 0 0 1 */
                   9660:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9661:   /*    7 0 1 1 */
                   9662:   /*    8 1 1 1 */
1.237     brouard  9663:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9664:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9665:   /* V5*age V5 known which value for nres?  */
                   9666:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9667:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9668:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9669:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9670:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9671:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9672:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9673:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9674:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9675:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9676:       k4++;;
                   9677:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9678:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9679:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9680:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9681:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9682:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9683:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9684:       k4q++;;
                   9685:     }
                   9686:   }
1.234     brouard  9687:   
1.235     brouard  9688:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9689:   return (0);
                   9690: }
1.235     brouard  9691: 
1.230     brouard  9692: int decodemodel( char model[], int lastobs)
                   9693:  /**< This routine decodes the model and returns:
1.224     brouard  9694:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9695:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9696:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9697:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9698:        * - cptcovage number of covariates with age*products =2
                   9699:        * - cptcovs number of simple covariates
                   9700:        * - 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
                   9701:        *     which is a new column after the 9 (ncovcol) variables. 
                   9702:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9703:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9704:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9705:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9706:        */
1.136     brouard  9707: {
1.238     brouard  9708:   int i, j, k, ks, v;
1.227     brouard  9709:   int  j1, k1, k2, k3, k4;
1.136     brouard  9710:   char modelsav[80];
1.145     brouard  9711:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9712:   char *strpt;
1.136     brouard  9713: 
1.145     brouard  9714:   /*removespace(model);*/
1.136     brouard  9715:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9716:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9717:     if (strstr(model,"AGE") !=0){
1.192     brouard  9718:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9719:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9720:       return 1;
                   9721:     }
1.141     brouard  9722:     if (strstr(model,"v") !=0){
                   9723:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9724:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9725:       return 1;
                   9726:     }
1.187     brouard  9727:     strcpy(modelsav,model); 
                   9728:     if ((strpt=strstr(model,"age*age")) !=0){
                   9729:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9730:       if(strpt != model){
1.234     brouard  9731:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9732:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9733:  corresponding column of parameters.\n",model);
1.234     brouard  9734:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9735:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9736:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9737:        return 1;
1.225     brouard  9738:       }
1.187     brouard  9739:       nagesqr=1;
                   9740:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9741:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9742:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9743:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9744:       else 
1.234     brouard  9745:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9746:     }else
                   9747:       nagesqr=0;
                   9748:     if (strlen(modelsav) >1){
                   9749:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9750:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9751:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9752:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9753:                     * cst, age and age*age 
                   9754:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9755:       /* including age products which are counted in cptcovage.
                   9756:        * but the covariates which are products must be treated 
                   9757:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9758:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9759:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9760:       
                   9761:       
1.187     brouard  9762:       /*   Design
                   9763:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9764:        *  <          ncovcol=8                >
                   9765:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9766:        *   k=  1    2      3       4     5       6      7        8
                   9767:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9768:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9769:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9770:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9771:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9772:        *  Tage[++cptcovage]=k
                   9773:        *       if products, new covar are created after ncovcol with k1
                   9774:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9775:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9776:        *  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
                   9777:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9778:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9779:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9780:        *  <          ncovcol=8                >
                   9781:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9782:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9783:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9784:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9785:        * p Tprod[1]@2={                         6, 5}
                   9786:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9787:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9788:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9789:        *How to reorganize?
                   9790:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9791:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9792:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9793:        * Struct []
                   9794:        */
1.225     brouard  9795:       
1.187     brouard  9796:       /* This loop fills the array Tvar from the string 'model'.*/
                   9797:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9798:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9799:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9800:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9801:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9802:       /*       k=1 Tvar[1]=2 (from V2) */
                   9803:       /*       k=5 Tvar[5] */
                   9804:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9805:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9806:       /*       } */
1.198     brouard  9807:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9808:       /*
                   9809:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9810:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9811:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9812:       }
1.187     brouard  9813:       cptcovage=0;
                   9814:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9815:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9816:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9817:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9818:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9819:        /*scanf("%d",i);*/
                   9820:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9821:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9822:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9823:            /* covar is not filled and then is empty */
                   9824:            cptcovprod--;
                   9825:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9826:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9827:            Typevar[k]=1;  /* 1 for age product */
                   9828:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9829:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9830:            /*printf("stre=%s ", stre);*/
                   9831:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9832:            cptcovprod--;
                   9833:            cutl(stre,strb,strc,'V');
                   9834:            Tvar[k]=atoi(stre);
                   9835:            Typevar[k]=1;  /* 1 for age product */
                   9836:            cptcovage++;
                   9837:            Tage[cptcovage]=k;
                   9838:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9839:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9840:            cptcovn++;
                   9841:            cptcovprodnoage++;k1++;
                   9842:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9843:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9844:                                                because this model-covariate is a construction we invent a new column
                   9845:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9846:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9847:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9848:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9849:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9850:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9851:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9852:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9853:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9854:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9855:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9856:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9857:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9858:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9859:            for (i=1; i<=lastobs;i++){
                   9860:              /* Computes the new covariate which is a product of
                   9861:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9862:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9863:            }
                   9864:          } /* End age is not in the model */
                   9865:        } /* End if model includes a product */
                   9866:        else { /* no more sum */
                   9867:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9868:          /*  scanf("%d",i);*/
                   9869:          cutl(strd,strc,strb,'V');
                   9870:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9871:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9872:          Tvar[k]=atoi(strd);
                   9873:          Typevar[k]=0;  /* 0 for simple covariates */
                   9874:        }
                   9875:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9876:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9877:                                  scanf("%d",i);*/
1.187     brouard  9878:       } /* end of loop + on total covariates */
                   9879:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9880:   } /* end if strlen(model == 0) */
1.136     brouard  9881:   
                   9882:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9883:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9884:   
1.136     brouard  9885:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9886:      printf("cptcovprod=%d ", cptcovprod);
                   9887:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9888:      scanf("%d ",i);*/
                   9889: 
                   9890: 
1.230     brouard  9891: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9892:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9893: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9894:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9895:    k =           1    2   3     4       5       6      7      8        9
                   9896:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9897:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9898:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9899:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9900:          Tmodelind[combination of covar]=k;
1.225     brouard  9901: */  
                   9902: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9903:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9904:   /* 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  9905:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9906:   printf("Model=%s\n\
                   9907: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9908: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9909: 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);
                   9910:   fprintf(ficlog,"Model=%s\n\
                   9911: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9912: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9913: 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  9914:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  9915:   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 */
                   9916:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  9917:       Fixed[k]= 0;
                   9918:       Dummy[k]= 0;
1.225     brouard  9919:       ncoveff++;
1.232     brouard  9920:       ncovf++;
1.234     brouard  9921:       nsd++;
                   9922:       modell[k].maintype= FTYPE;
                   9923:       TvarsD[nsd]=Tvar[k];
                   9924:       TvarsDind[nsd]=k;
                   9925:       TvarF[ncovf]=Tvar[k];
                   9926:       TvarFind[ncovf]=k;
                   9927:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9928:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9929:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   9930:       Fixed[k]= 0;
                   9931:       Dummy[k]= 0;
                   9932:       ncoveff++;
                   9933:       ncovf++;
                   9934:       modell[k].maintype= FTYPE;
                   9935:       TvarF[ncovf]=Tvar[k];
                   9936:       TvarFind[ncovf]=k;
1.230     brouard  9937:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  9938:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  9939:     }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  9940:       Fixed[k]= 0;
                   9941:       Dummy[k]= 1;
1.230     brouard  9942:       nqfveff++;
1.234     brouard  9943:       modell[k].maintype= FTYPE;
                   9944:       modell[k].subtype= FQ;
                   9945:       nsq++;
                   9946:       TvarsQ[nsq]=Tvar[k];
                   9947:       TvarsQind[nsq]=k;
1.232     brouard  9948:       ncovf++;
1.234     brouard  9949:       TvarF[ncovf]=Tvar[k];
                   9950:       TvarFind[ncovf]=k;
1.231     brouard  9951:       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  9952:       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  9953:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  9954:       Fixed[k]= 1;
                   9955:       Dummy[k]= 0;
1.225     brouard  9956:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  9957:       modell[k].maintype= VTYPE;
                   9958:       modell[k].subtype= VD;
                   9959:       nsd++;
                   9960:       TvarsD[nsd]=Tvar[k];
                   9961:       TvarsDind[nsd]=k;
                   9962:       ncovv++; /* Only simple time varying variables */
                   9963:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9964:       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  9965:       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 */
                   9966:       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  9967:       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);
                   9968:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  9969:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  9970:       Fixed[k]= 1;
                   9971:       Dummy[k]= 1;
                   9972:       nqtveff++;
                   9973:       modell[k].maintype= VTYPE;
                   9974:       modell[k].subtype= VQ;
                   9975:       ncovv++; /* Only simple time varying variables */
                   9976:       nsq++;
                   9977:       TvarsQ[nsq]=Tvar[k];
                   9978:       TvarsQind[nsq]=k;
                   9979:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9980:       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  9981:       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 */
                   9982:       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  9983:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   9984:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   9985:       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  9986:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  9987:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  9988:       ncova++;
                   9989:       TvarA[ncova]=Tvar[k];
                   9990:       TvarAind[ncova]=k;
1.231     brouard  9991:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  9992:        Fixed[k]= 2;
                   9993:        Dummy[k]= 2;
                   9994:        modell[k].maintype= ATYPE;
                   9995:        modell[k].subtype= APFD;
                   9996:        /* ncoveff++; */
1.227     brouard  9997:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  9998:        Fixed[k]= 2;
                   9999:        Dummy[k]= 3;
                   10000:        modell[k].maintype= ATYPE;
                   10001:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10002:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10003:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10004:        Fixed[k]= 3;
                   10005:        Dummy[k]= 2;
                   10006:        modell[k].maintype= ATYPE;
                   10007:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10008:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10009:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10010:        Fixed[k]= 3;
                   10011:        Dummy[k]= 3;
                   10012:        modell[k].maintype= ATYPE;
                   10013:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10014:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10015:       }
                   10016:     }else if (Typevar[k] == 2) {  /* product without age */
                   10017:       k1=Tposprod[k];
                   10018:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10019:        if(Tvard[k1][2] <=ncovcol){
                   10020:          Fixed[k]= 1;
                   10021:          Dummy[k]= 0;
                   10022:          modell[k].maintype= FTYPE;
                   10023:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10024:          ncovf++; /* Fixed variables without age */
                   10025:          TvarF[ncovf]=Tvar[k];
                   10026:          TvarFind[ncovf]=k;
                   10027:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10028:          Fixed[k]= 0;  /* or 2 ?*/
                   10029:          Dummy[k]= 1;
                   10030:          modell[k].maintype= FTYPE;
                   10031:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10032:          ncovf++; /* Varying variables without age */
                   10033:          TvarF[ncovf]=Tvar[k];
                   10034:          TvarFind[ncovf]=k;
                   10035:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10036:          Fixed[k]= 1;
                   10037:          Dummy[k]= 0;
                   10038:          modell[k].maintype= VTYPE;
                   10039:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10040:          ncovv++; /* Varying variables without age */
                   10041:          TvarV[ncovv]=Tvar[k];
                   10042:          TvarVind[ncovv]=k;
                   10043:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10044:          Fixed[k]= 1;
                   10045:          Dummy[k]= 1;
                   10046:          modell[k].maintype= VTYPE;
                   10047:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10048:          ncovv++; /* Varying variables without age */
                   10049:          TvarV[ncovv]=Tvar[k];
                   10050:          TvarVind[ncovv]=k;
                   10051:        }
1.227     brouard  10052:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10053:        if(Tvard[k1][2] <=ncovcol){
                   10054:          Fixed[k]= 0;  /* or 2 ?*/
                   10055:          Dummy[k]= 1;
                   10056:          modell[k].maintype= FTYPE;
                   10057:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10058:          ncovf++; /* Fixed variables without age */
                   10059:          TvarF[ncovf]=Tvar[k];
                   10060:          TvarFind[ncovf]=k;
                   10061:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10062:          Fixed[k]= 1;
                   10063:          Dummy[k]= 1;
                   10064:          modell[k].maintype= VTYPE;
                   10065:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10066:          ncovv++; /* Varying variables without age */
                   10067:          TvarV[ncovv]=Tvar[k];
                   10068:          TvarVind[ncovv]=k;
                   10069:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10070:          Fixed[k]= 1;
                   10071:          Dummy[k]= 1;
                   10072:          modell[k].maintype= VTYPE;
                   10073:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10074:          ncovv++; /* Varying variables without age */
                   10075:          TvarV[ncovv]=Tvar[k];
                   10076:          TvarVind[ncovv]=k;
                   10077:          ncovv++; /* Varying variables without age */
                   10078:          TvarV[ncovv]=Tvar[k];
                   10079:          TvarVind[ncovv]=k;
                   10080:        }
1.227     brouard  10081:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10082:        if(Tvard[k1][2] <=ncovcol){
                   10083:          Fixed[k]= 1;
                   10084:          Dummy[k]= 1;
                   10085:          modell[k].maintype= VTYPE;
                   10086:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10087:          ncovv++; /* Varying variables without age */
                   10088:          TvarV[ncovv]=Tvar[k];
                   10089:          TvarVind[ncovv]=k;
                   10090:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10091:          Fixed[k]= 1;
                   10092:          Dummy[k]= 1;
                   10093:          modell[k].maintype= VTYPE;
                   10094:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10095:          ncovv++; /* Varying variables without age */
                   10096:          TvarV[ncovv]=Tvar[k];
                   10097:          TvarVind[ncovv]=k;
                   10098:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10099:          Fixed[k]= 1;
                   10100:          Dummy[k]= 0;
                   10101:          modell[k].maintype= VTYPE;
                   10102:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10103:          ncovv++; /* Varying variables without age */
                   10104:          TvarV[ncovv]=Tvar[k];
                   10105:          TvarVind[ncovv]=k;
                   10106:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10107:          Fixed[k]= 1;
                   10108:          Dummy[k]= 1;
                   10109:          modell[k].maintype= VTYPE;
                   10110:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10111:          ncovv++; /* Varying variables without age */
                   10112:          TvarV[ncovv]=Tvar[k];
                   10113:          TvarVind[ncovv]=k;
                   10114:        }
1.227     brouard  10115:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10116:        if(Tvard[k1][2] <=ncovcol){
                   10117:          Fixed[k]= 1;
                   10118:          Dummy[k]= 1;
                   10119:          modell[k].maintype= VTYPE;
                   10120:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10121:          ncovv++; /* Varying variables without age */
                   10122:          TvarV[ncovv]=Tvar[k];
                   10123:          TvarVind[ncovv]=k;
                   10124:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10125:          Fixed[k]= 1;
                   10126:          Dummy[k]= 1;
                   10127:          modell[k].maintype= VTYPE;
                   10128:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10129:          ncovv++; /* Varying variables without age */
                   10130:          TvarV[ncovv]=Tvar[k];
                   10131:          TvarVind[ncovv]=k;
                   10132:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10133:          Fixed[k]= 1;
                   10134:          Dummy[k]= 1;
                   10135:          modell[k].maintype= VTYPE;
                   10136:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10137:          ncovv++; /* Varying variables without age */
                   10138:          TvarV[ncovv]=Tvar[k];
                   10139:          TvarVind[ncovv]=k;
                   10140:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10141:          Fixed[k]= 1;
                   10142:          Dummy[k]= 1;
                   10143:          modell[k].maintype= VTYPE;
                   10144:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10145:          ncovv++; /* Varying variables without age */
                   10146:          TvarV[ncovv]=Tvar[k];
                   10147:          TvarVind[ncovv]=k;
                   10148:        }
1.227     brouard  10149:       }else{
1.240     brouard  10150:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10151:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10152:       } /*end k1*/
1.225     brouard  10153:     }else{
1.226     brouard  10154:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10155:       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  10156:     }
1.227     brouard  10157:     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  10158:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10159:     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]);
                   10160:   }
                   10161:   /* Searching for doublons in the model */
                   10162:   for(k1=1; k1<= cptcovt;k1++){
                   10163:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10164:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10165:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10166:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10167:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10168:            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]);
                   10169:            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  10170:            return(1);
                   10171:          }
                   10172:        }else if (Typevar[k1] ==2){
                   10173:          k3=Tposprod[k1];
                   10174:          k4=Tposprod[k2];
                   10175:          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])) ){
                   10176:            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]]);
                   10177:            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);
                   10178:            return(1);
                   10179:          }
                   10180:        }
1.227     brouard  10181:       }
                   10182:     }
1.225     brouard  10183:   }
                   10184:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10185:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10186:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10187:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10188:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10189:   /*endread:*/
1.225     brouard  10190:   printf("Exiting decodemodel: ");
                   10191:   return (1);
1.136     brouard  10192: }
                   10193: 
1.169     brouard  10194: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10195: {/* Check ages at death */
1.136     brouard  10196:   int i, m;
1.218     brouard  10197:   int firstone=0;
                   10198:   
1.136     brouard  10199:   for (i=1; i<=imx; i++) {
                   10200:     for(m=2; (m<= maxwav); m++) {
                   10201:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10202:        anint[m][i]=9999;
1.216     brouard  10203:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10204:          s[m][i]=-1;
1.136     brouard  10205:       }
                   10206:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10207:        *nberr = *nberr + 1;
1.218     brouard  10208:        if(firstone == 0){
                   10209:          firstone=1;
1.260     brouard  10210:        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  10211:        }
1.262     brouard  10212:        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  10213:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10214:       }
                   10215:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10216:        (*nberr)++;
1.259     brouard  10217:        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  10218:        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  10219:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10220:       }
                   10221:     }
                   10222:   }
                   10223: 
                   10224:   for (i=1; i<=imx; i++)  {
                   10225:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10226:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10227:       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  10228:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10229:          if(agedc[i]>0){
                   10230:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10231:              agev[m][i]=agedc[i];
1.214     brouard  10232:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10233:            }else {
1.136     brouard  10234:              if ((int)andc[i]!=9999){
                   10235:                nbwarn++;
                   10236:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10237:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10238:                agev[m][i]=-1;
                   10239:              }
                   10240:            }
1.169     brouard  10241:          } /* agedc > 0 */
1.214     brouard  10242:        } /* end if */
1.136     brouard  10243:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10244:                                 years but with the precision of a month */
                   10245:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10246:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10247:            agev[m][i]=1;
                   10248:          else if(agev[m][i] < *agemin){ 
                   10249:            *agemin=agev[m][i];
                   10250:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10251:          }
                   10252:          else if(agev[m][i] >*agemax){
                   10253:            *agemax=agev[m][i];
1.156     brouard  10254:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10255:          }
                   10256:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10257:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10258:        } /* en if 9*/
1.136     brouard  10259:        else { /* =9 */
1.214     brouard  10260:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10261:          agev[m][i]=1;
                   10262:          s[m][i]=-1;
                   10263:        }
                   10264:       }
1.214     brouard  10265:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10266:        agev[m][i]=1;
1.214     brouard  10267:       else{
                   10268:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10269:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10270:        agev[m][i]=0;
                   10271:       }
                   10272:     } /* End for lastpass */
                   10273:   }
1.136     brouard  10274:     
                   10275:   for (i=1; i<=imx; i++)  {
                   10276:     for(m=firstpass; (m<=lastpass); m++){
                   10277:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10278:        (*nberr)++;
1.136     brouard  10279:        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);     
                   10280:        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);     
                   10281:        return 1;
                   10282:       }
                   10283:     }
                   10284:   }
                   10285: 
                   10286:   /*for (i=1; i<=imx; i++){
                   10287:   for (m=firstpass; (m<lastpass); m++){
                   10288:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10289: }
                   10290: 
                   10291: }*/
                   10292: 
                   10293: 
1.139     brouard  10294:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10295:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10296: 
                   10297:   return (0);
1.164     brouard  10298:  /* endread:*/
1.136     brouard  10299:     printf("Exiting calandcheckages: ");
                   10300:     return (1);
                   10301: }
                   10302: 
1.172     brouard  10303: #if defined(_MSC_VER)
                   10304: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10305: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10306: //#include "stdafx.h"
                   10307: //#include <stdio.h>
                   10308: //#include <tchar.h>
                   10309: //#include <windows.h>
                   10310: //#include <iostream>
                   10311: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10312: 
                   10313: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10314: 
                   10315: BOOL IsWow64()
                   10316: {
                   10317:        BOOL bIsWow64 = FALSE;
                   10318: 
                   10319:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10320:        //  (HANDLE, PBOOL);
                   10321: 
                   10322:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10323: 
                   10324:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10325:        const char funcName[] = "IsWow64Process";
                   10326:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10327:                GetProcAddress(module, funcName);
                   10328: 
                   10329:        if (NULL != fnIsWow64Process)
                   10330:        {
                   10331:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10332:                        &bIsWow64))
                   10333:                        //throw std::exception("Unknown error");
                   10334:                        printf("Unknown error\n");
                   10335:        }
                   10336:        return bIsWow64 != FALSE;
                   10337: }
                   10338: #endif
1.177     brouard  10339: 
1.191     brouard  10340: void syscompilerinfo(int logged)
1.292     brouard  10341: {
                   10342: #include <stdint.h>
                   10343: 
                   10344:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10345:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10346:    /* /GS /W3 /Gy
                   10347:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10348:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10349:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10350:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10351:    */ 
                   10352:    /* 64 bits */
1.185     brouard  10353:    /*
                   10354:      /GS /W3 /Gy
                   10355:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10356:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10357:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10358:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10359:    /* Optimization are useless and O3 is slower than O2 */
                   10360:    /*
                   10361:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10362:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10363:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10364:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10365:    */
1.186     brouard  10366:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10367:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10368:       /PDB:"visual studio
                   10369:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10370:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10371:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10372:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10373:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10374:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10375:       uiAccess='false'"
                   10376:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10377:       /NOLOGO /TLBID:1
                   10378:    */
1.292     brouard  10379: 
                   10380: 
1.177     brouard  10381: #if defined __INTEL_COMPILER
1.178     brouard  10382: #if defined(__GNUC__)
                   10383:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10384: #endif
1.177     brouard  10385: #elif defined(__GNUC__) 
1.179     brouard  10386: #ifndef  __APPLE__
1.174     brouard  10387: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10388: #endif
1.177     brouard  10389:    struct utsname sysInfo;
1.178     brouard  10390:    int cross = CROSS;
                   10391:    if (cross){
                   10392:           printf("Cross-");
1.191     brouard  10393:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10394:    }
1.174     brouard  10395: #endif
                   10396: 
1.191     brouard  10397:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10398: #if defined(__clang__)
1.191     brouard  10399:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10400: #endif
                   10401: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10402:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10403: #endif
                   10404: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10405:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10406: #endif
                   10407: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10408:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10409: #endif
                   10410: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10411:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10412: #endif
                   10413: #if defined(_MSC_VER)
1.191     brouard  10414:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10415: #endif
                   10416: #if defined(__PGI)
1.191     brouard  10417:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10418: #endif
                   10419: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10420:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10421: #endif
1.191     brouard  10422:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10423:    
1.167     brouard  10424: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10425: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10426:     // Windows (x64 and x86)
1.191     brouard  10427:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10428: #elif __unix__ // all unices, not all compilers
                   10429:     // Unix
1.191     brouard  10430:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10431: #elif __linux__
                   10432:     // linux
1.191     brouard  10433:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10434: #elif __APPLE__
1.174     brouard  10435:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10436:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10437: #endif
                   10438: 
                   10439: /*  __MINGW32__          */
                   10440: /*  __CYGWIN__  */
                   10441: /* __MINGW64__  */
                   10442: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10443: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10444: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10445: /* _WIN64  // Defined for applications for Win64. */
                   10446: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10447: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10448: 
1.167     brouard  10449: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10450:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10451: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10452:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10453: #else
1.191     brouard  10454:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10455: #endif
                   10456: 
1.169     brouard  10457: #if defined(__GNUC__)
                   10458: # if defined(__GNUC_PATCHLEVEL__)
                   10459: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10460:                             + __GNUC_MINOR__ * 100 \
                   10461:                             + __GNUC_PATCHLEVEL__)
                   10462: # else
                   10463: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10464:                             + __GNUC_MINOR__ * 100)
                   10465: # endif
1.174     brouard  10466:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10467:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10468: 
                   10469:    if (uname(&sysInfo) != -1) {
                   10470:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10471:         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  10472:    }
                   10473:    else
                   10474:       perror("uname() error");
1.179     brouard  10475:    //#ifndef __INTEL_COMPILER 
                   10476: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10477:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10478:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10479: #endif
1.169     brouard  10480: #endif
1.172     brouard  10481: 
1.286     brouard  10482:    //   void main ()
1.172     brouard  10483:    //   {
1.169     brouard  10484: #if defined(_MSC_VER)
1.174     brouard  10485:    if (IsWow64()){
1.191     brouard  10486:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10487:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10488:    }
                   10489:    else{
1.191     brouard  10490:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10491:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10492:    }
1.172     brouard  10493:    //     printf("\nPress Enter to continue...");
                   10494:    //     getchar();
                   10495:    //   }
                   10496: 
1.169     brouard  10497: #endif
                   10498:    
1.167     brouard  10499: 
1.219     brouard  10500: }
1.136     brouard  10501: 
1.219     brouard  10502: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10503:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10504:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10505:   /* double ftolpl = 1.e-10; */
1.180     brouard  10506:   double age, agebase, agelim;
1.203     brouard  10507:   double tot;
1.180     brouard  10508: 
1.202     brouard  10509:   strcpy(filerespl,"PL_");
                   10510:   strcat(filerespl,fileresu);
                   10511:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10512:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10513:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10514:   }
1.288     brouard  10515:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10516:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10517:   pstamp(ficrespl);
1.288     brouard  10518:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10519:   fprintf(ficrespl,"#Age ");
                   10520:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10521:   fprintf(ficrespl,"\n");
1.180     brouard  10522:   
1.219     brouard  10523:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10524: 
1.219     brouard  10525:   agebase=ageminpar;
                   10526:   agelim=agemaxpar;
1.180     brouard  10527: 
1.227     brouard  10528:   /* i1=pow(2,ncoveff); */
1.234     brouard  10529:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10530:   if (cptcovn < 1){i1=1;}
1.180     brouard  10531: 
1.238     brouard  10532:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10533:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10534:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10535:        continue;
1.235     brouard  10536: 
1.238     brouard  10537:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10538:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10539:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10540:       /* k=k+1; */
                   10541:       /* to clean */
                   10542:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10543:       fprintf(ficrespl,"#******");
                   10544:       printf("#******");
                   10545:       fprintf(ficlog,"#******");
                   10546:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10547:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10548:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10549:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10550:       }
                   10551:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10552:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10553:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10554:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10555:       }
                   10556:       fprintf(ficrespl,"******\n");
                   10557:       printf("******\n");
                   10558:       fprintf(ficlog,"******\n");
                   10559:       if(invalidvarcomb[k]){
                   10560:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10561:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10562:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10563:        continue;
                   10564:       }
1.219     brouard  10565: 
1.238     brouard  10566:       fprintf(ficrespl,"#Age ");
                   10567:       for(j=1;j<=cptcoveff;j++) {
                   10568:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10569:       }
                   10570:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10571:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10572:     
1.238     brouard  10573:       for (age=agebase; age<=agelim; age++){
                   10574:        /* for (age=agebase; age<=agebase; age++){ */
                   10575:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10576:        fprintf(ficrespl,"%.0f ",age );
                   10577:        for(j=1;j<=cptcoveff;j++)
                   10578:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10579:        tot=0.;
                   10580:        for(i=1; i<=nlstate;i++){
                   10581:          tot +=  prlim[i][i];
                   10582:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10583:        }
                   10584:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10585:       } /* Age */
                   10586:       /* was end of cptcod */
                   10587:     } /* cptcov */
                   10588:   } /* nres */
1.219     brouard  10589:   return 0;
1.180     brouard  10590: }
                   10591: 
1.218     brouard  10592: 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  10593:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10594:        
                   10595:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10596:    * at any age between ageminpar and agemaxpar
                   10597:         */
1.235     brouard  10598:   int i, j, k, i1, nres=0 ;
1.217     brouard  10599:   /* double ftolpl = 1.e-10; */
                   10600:   double age, agebase, agelim;
                   10601:   double tot;
1.218     brouard  10602:   /* double ***mobaverage; */
                   10603:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10604: 
                   10605:   strcpy(fileresplb,"PLB_");
                   10606:   strcat(fileresplb,fileresu);
                   10607:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10608:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10609:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10610:   }
1.288     brouard  10611:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10612:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10613:   pstamp(ficresplb);
1.288     brouard  10614:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10615:   fprintf(ficresplb,"#Age ");
                   10616:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10617:   fprintf(ficresplb,"\n");
                   10618:   
1.218     brouard  10619:   
                   10620:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10621:   
                   10622:   agebase=ageminpar;
                   10623:   agelim=agemaxpar;
                   10624:   
                   10625:   
1.227     brouard  10626:   i1=pow(2,cptcoveff);
1.218     brouard  10627:   if (cptcovn < 1){i1=1;}
1.227     brouard  10628:   
1.238     brouard  10629:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10630:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10631:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10632:        continue;
                   10633:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10634:       fprintf(ficresplb,"#******");
                   10635:       printf("#******");
                   10636:       fprintf(ficlog,"#******");
                   10637:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10638:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10639:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10640:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10641:       }
                   10642:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10643:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10644:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10645:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10646:       }
                   10647:       fprintf(ficresplb,"******\n");
                   10648:       printf("******\n");
                   10649:       fprintf(ficlog,"******\n");
                   10650:       if(invalidvarcomb[k]){
                   10651:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10652:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10653:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10654:        continue;
                   10655:       }
1.218     brouard  10656:     
1.238     brouard  10657:       fprintf(ficresplb,"#Age ");
                   10658:       for(j=1;j<=cptcoveff;j++) {
                   10659:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10660:       }
                   10661:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10662:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10663:     
                   10664:     
1.238     brouard  10665:       for (age=agebase; age<=agelim; age++){
                   10666:        /* for (age=agebase; age<=agebase; age++){ */
                   10667:        if(mobilavproj > 0){
                   10668:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10669:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10670:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10671:        }else if (mobilavproj == 0){
                   10672:          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);
                   10673:          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);
                   10674:          exit(1);
                   10675:        }else{
                   10676:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10677:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10678:          /* printf("TOTOT\n"); */
                   10679:           /* exit(1); */
1.238     brouard  10680:        }
                   10681:        fprintf(ficresplb,"%.0f ",age );
                   10682:        for(j=1;j<=cptcoveff;j++)
                   10683:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10684:        tot=0.;
                   10685:        for(i=1; i<=nlstate;i++){
                   10686:          tot +=  bprlim[i][i];
                   10687:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10688:        }
                   10689:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10690:       } /* Age */
                   10691:       /* was end of cptcod */
1.255     brouard  10692:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10693:     } /* end of any combination */
                   10694:   } /* end of nres */  
1.218     brouard  10695:   /* hBijx(p, bage, fage); */
                   10696:   /* fclose(ficrespijb); */
                   10697:   
                   10698:   return 0;
1.217     brouard  10699: }
1.218     brouard  10700:  
1.180     brouard  10701: int hPijx(double *p, int bage, int fage){
                   10702:     /*------------- h Pij x at various ages ------------*/
                   10703: 
                   10704:   int stepsize;
                   10705:   int agelim;
                   10706:   int hstepm;
                   10707:   int nhstepm;
1.235     brouard  10708:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10709: 
                   10710:   double agedeb;
                   10711:   double ***p3mat;
                   10712: 
1.201     brouard  10713:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10714:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10715:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10716:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10717:     }
                   10718:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10719:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10720:   
                   10721:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10722:     /*if (stepm<=24) stepsize=2;*/
                   10723: 
                   10724:     agelim=AGESUP;
                   10725:     hstepm=stepsize*YEARM; /* Every year of age */
                   10726:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10727:                
1.180     brouard  10728:     /* hstepm=1;   aff par mois*/
                   10729:     pstamp(ficrespij);
                   10730:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10731:     i1= pow(2,cptcoveff);
1.218     brouard  10732:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10733:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10734:                /*      k=k+1;  */
1.235     brouard  10735:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10736:     for(k=1; k<=i1;k++){
1.253     brouard  10737:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10738:        continue;
1.183     brouard  10739:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10740:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10741:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10742:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10743:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10744:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10745:       }
1.183     brouard  10746:       fprintf(ficrespij,"******\n");
                   10747:       
                   10748:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10749:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10750:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10751:        
                   10752:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10753:        
1.183     brouard  10754:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10755:        oldm=oldms;savm=savms;
1.235     brouard  10756:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10757:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10758:        for(i=1; i<=nlstate;i++)
                   10759:          for(j=1; j<=nlstate+ndeath;j++)
                   10760:            fprintf(ficrespij," %1d-%1d",i,j);
                   10761:        fprintf(ficrespij,"\n");
                   10762:        for (h=0; h<=nhstepm; h++){
                   10763:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10764:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10765:          for(i=1; i<=nlstate;i++)
                   10766:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10767:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10768:          fprintf(ficrespij,"\n");
                   10769:        }
1.183     brouard  10770:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10771:        fprintf(ficrespij,"\n");
                   10772:       }
1.180     brouard  10773:       /*}*/
                   10774:     }
1.218     brouard  10775:     return 0;
1.180     brouard  10776: }
1.218     brouard  10777:  
                   10778:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10779:     /*------------- h Bij x at various ages ------------*/
                   10780: 
                   10781:   int stepsize;
1.218     brouard  10782:   /* int agelim; */
                   10783:        int ageminl;
1.217     brouard  10784:   int hstepm;
                   10785:   int nhstepm;
1.238     brouard  10786:   int h, i, i1, j, k, nres;
1.218     brouard  10787:        
1.217     brouard  10788:   double agedeb;
                   10789:   double ***p3mat;
1.218     brouard  10790:        
                   10791:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10792:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10793:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10794:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10795:   }
                   10796:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10797:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10798:   
                   10799:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10800:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10801:   
1.218     brouard  10802:   /* agelim=AGESUP; */
1.289     brouard  10803:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10804:   hstepm=stepsize*YEARM; /* Every year of age */
                   10805:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10806:   
                   10807:   /* hstepm=1;   aff par mois*/
                   10808:   pstamp(ficrespijb);
1.255     brouard  10809:   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  10810:   i1= pow(2,cptcoveff);
1.218     brouard  10811:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10812:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10813:   /*   k=k+1;  */
1.238     brouard  10814:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10815:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10816:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10817:        continue;
                   10818:       fprintf(ficrespijb,"\n#****** ");
                   10819:       for(j=1;j<=cptcoveff;j++)
                   10820:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10821:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10822:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10823:       }
                   10824:       fprintf(ficrespijb,"******\n");
1.264     brouard  10825:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10826:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10827:        continue;
                   10828:       }
                   10829:       
                   10830:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10831:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10832:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  10833:        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 */
                   10834:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  10835:        
                   10836:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10837:        
1.266     brouard  10838:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10839:        /* and memory limitations if stepm is small */
                   10840: 
1.238     brouard  10841:        /* oldm=oldms;savm=savms; */
                   10842:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10843:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10844:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10845:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10846:        for(i=1; i<=nlstate;i++)
                   10847:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10848:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10849:        fprintf(ficrespijb,"\n");
1.238     brouard  10850:        for (h=0; h<=nhstepm; h++){
                   10851:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10852:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10853:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10854:          for(i=1; i<=nlstate;i++)
                   10855:            for(j=1; j<=nlstate+ndeath;j++)
                   10856:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10857:          fprintf(ficrespijb,"\n");
                   10858:        }
                   10859:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10860:        fprintf(ficrespijb,"\n");
                   10861:       } /* end age deb */
                   10862:     } /* end combination */
                   10863:   } /* end nres */
1.218     brouard  10864:   return 0;
                   10865:  } /*  hBijx */
1.217     brouard  10866: 
1.180     brouard  10867: 
1.136     brouard  10868: /***********************************************/
                   10869: /**************** Main Program *****************/
                   10870: /***********************************************/
                   10871: 
                   10872: int main(int argc, char *argv[])
                   10873: {
                   10874: #ifdef GSL
                   10875:   const gsl_multimin_fminimizer_type *T;
                   10876:   size_t iteri = 0, it;
                   10877:   int rval = GSL_CONTINUE;
                   10878:   int status = GSL_SUCCESS;
                   10879:   double ssval;
                   10880: #endif
                   10881:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10882:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10883:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10884:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10885:   int jj, ll, li, lj, lk;
1.136     brouard  10886:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10887:   int num_filled;
1.136     brouard  10888:   int itimes;
                   10889:   int NDIM=2;
                   10890:   int vpopbased=0;
1.235     brouard  10891:   int nres=0;
1.258     brouard  10892:   int endishere=0;
1.277     brouard  10893:   int noffset=0;
1.274     brouard  10894:   int ncurrv=0; /* Temporary variable */
                   10895:   
1.164     brouard  10896:   char ca[32], cb[32];
1.136     brouard  10897:   /*  FILE *fichtm; *//* Html File */
                   10898:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10899:   struct stat info;
1.191     brouard  10900:   double agedeb=0.;
1.194     brouard  10901: 
                   10902:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10903:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10904: 
1.165     brouard  10905:   double fret;
1.191     brouard  10906:   double dum=0.; /* Dummy variable */
1.136     brouard  10907:   double ***p3mat;
1.218     brouard  10908:   /* double ***mobaverage; */
1.164     brouard  10909: 
                   10910:   char line[MAXLINE];
1.197     brouard  10911:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   10912: 
1.234     brouard  10913:   char  modeltemp[MAXLINE];
1.230     brouard  10914:   char resultline[MAXLINE];
                   10915:   
1.136     brouard  10916:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  10917:   char *tok, *val; /* pathtot */
1.290     brouard  10918:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  10919:   int c,  h , cpt, c2;
1.191     brouard  10920:   int jl=0;
                   10921:   int i1, j1, jk, stepsize=0;
1.194     brouard  10922:   int count=0;
                   10923: 
1.164     brouard  10924:   int *tab; 
1.136     brouard  10925:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  10926:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   10927:   /* double anprojf, mprojf, jprojf; */
                   10928:   /* double jintmean,mintmean,aintmean;   */
                   10929:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10930:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10931:   double yrfproj= 10.0; /* Number of years of forward projections */
                   10932:   double yrbproj= 10.0; /* Number of years of backward projections */
                   10933:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  10934:   int mobilav=0,popforecast=0;
1.191     brouard  10935:   int hstepm=0, nhstepm=0;
1.136     brouard  10936:   int agemortsup;
                   10937:   float  sumlpop=0.;
                   10938:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   10939:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   10940: 
1.191     brouard  10941:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  10942:   double ftolpl=FTOL;
                   10943:   double **prlim;
1.217     brouard  10944:   double **bprlim;
1.136     brouard  10945:   double ***param; /* Matrix of parameters */
1.251     brouard  10946:   double ***paramstart; /* Matrix of starting parameter values */
                   10947:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  10948:   double **matcov; /* Matrix of covariance */
1.203     brouard  10949:   double **hess; /* Hessian matrix */
1.136     brouard  10950:   double ***delti3; /* Scale */
                   10951:   double *delti; /* Scale */
                   10952:   double ***eij, ***vareij;
                   10953:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  10954: 
1.136     brouard  10955:   double *epj, vepp;
1.164     brouard  10956: 
1.273     brouard  10957:   double dateprev1, dateprev2;
1.296     brouard  10958:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   10959:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   10960: 
1.217     brouard  10961: 
1.136     brouard  10962:   double **ximort;
1.145     brouard  10963:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  10964:   int *dcwave;
                   10965: 
1.164     brouard  10966:   char z[1]="c";
1.136     brouard  10967: 
                   10968:   /*char  *strt;*/
                   10969:   char strtend[80];
1.126     brouard  10970: 
1.164     brouard  10971: 
1.126     brouard  10972: /*   setlocale (LC_ALL, ""); */
                   10973: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   10974: /*   textdomain (PACKAGE); */
                   10975: /*   setlocale (LC_CTYPE, ""); */
                   10976: /*   setlocale (LC_MESSAGES, ""); */
                   10977: 
                   10978:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  10979:   rstart_time = time(NULL);  
                   10980:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   10981:   start_time = *localtime(&rstart_time);
1.126     brouard  10982:   curr_time=start_time;
1.157     brouard  10983:   /*tml = *localtime(&start_time.tm_sec);*/
                   10984:   /* strcpy(strstart,asctime(&tml)); */
                   10985:   strcpy(strstart,asctime(&start_time));
1.126     brouard  10986: 
                   10987: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  10988: /*  tp.tm_sec = tp.tm_sec +86400; */
                   10989: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  10990: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   10991: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   10992: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  10993: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  10994: /*   strt=asctime(&tmg); */
                   10995: /*   printf("Time(after) =%s",strstart);  */
                   10996: /*  (void) time (&time_value);
                   10997: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   10998: *  tm = *localtime(&time_value);
                   10999: *  strstart=asctime(&tm);
                   11000: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11001: */
                   11002: 
                   11003:   nberr=0; /* Number of errors and warnings */
                   11004:   nbwarn=0;
1.184     brouard  11005: #ifdef WIN32
                   11006:   _getcwd(pathcd, size);
                   11007: #else
1.126     brouard  11008:   getcwd(pathcd, size);
1.184     brouard  11009: #endif
1.191     brouard  11010:   syscompilerinfo(0);
1.196     brouard  11011:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11012:   if(argc <=1){
                   11013:     printf("\nEnter the parameter file name: ");
1.205     brouard  11014:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11015:       printf("ERROR Empty parameter file name\n");
                   11016:       goto end;
                   11017:     }
1.126     brouard  11018:     i=strlen(pathr);
                   11019:     if(pathr[i-1]=='\n')
                   11020:       pathr[i-1]='\0';
1.156     brouard  11021:     i=strlen(pathr);
1.205     brouard  11022:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11023:       pathr[i-1]='\0';
1.205     brouard  11024:     }
                   11025:     i=strlen(pathr);
                   11026:     if( i==0 ){
                   11027:       printf("ERROR Empty parameter file name\n");
                   11028:       goto end;
                   11029:     }
                   11030:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11031:       printf("Pathr |%s|\n",pathr);
                   11032:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11033:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11034:       strcpy (pathtot, val);
                   11035:       if(pathr[0] == '\0') break; /* Dirty */
                   11036:     }
                   11037:   }
1.281     brouard  11038:   else if (argc<=2){
                   11039:     strcpy(pathtot,argv[1]);
                   11040:   }
1.126     brouard  11041:   else{
                   11042:     strcpy(pathtot,argv[1]);
1.281     brouard  11043:     strcpy(z,argv[2]);
                   11044:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11045:   }
                   11046:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11047:   /*cygwin_split_path(pathtot,path,optionfile);
                   11048:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11049:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11050: 
                   11051:   /* Split argv[0], imach program to get pathimach */
                   11052:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11053:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11054:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11055:  /*   strcpy(pathimach,argv[0]); */
                   11056:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11057:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11058:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11059: #ifdef WIN32
                   11060:   _chdir(path); /* Can be a relative path */
                   11061:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11062: #else
1.126     brouard  11063:   chdir(path); /* Can be a relative path */
1.184     brouard  11064:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11065: #endif
                   11066:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11067:   strcpy(command,"mkdir ");
                   11068:   strcat(command,optionfilefiname);
                   11069:   if((outcmd=system(command)) != 0){
1.169     brouard  11070:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11071:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11072:     /* fclose(ficlog); */
                   11073: /*     exit(1); */
                   11074:   }
                   11075: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11076: /*     perror("mkdir"); */
                   11077: /*   } */
                   11078: 
                   11079:   /*-------- arguments in the command line --------*/
                   11080: 
1.186     brouard  11081:   /* Main Log file */
1.126     brouard  11082:   strcat(filelog, optionfilefiname);
                   11083:   strcat(filelog,".log");    /* */
                   11084:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11085:     printf("Problem with logfile %s\n",filelog);
                   11086:     goto end;
                   11087:   }
                   11088:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11089:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11090:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11091:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11092:  path=%s \n\
                   11093:  optionfile=%s\n\
                   11094:  optionfilext=%s\n\
1.156     brouard  11095:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11096: 
1.197     brouard  11097:   syscompilerinfo(1);
1.167     brouard  11098: 
1.126     brouard  11099:   printf("Local time (at start):%s",strstart);
                   11100:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11101:   fflush(ficlog);
                   11102: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11103: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11104: 
                   11105:   /* */
                   11106:   strcpy(fileres,"r");
                   11107:   strcat(fileres, optionfilefiname);
1.201     brouard  11108:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11109:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11110:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11111: 
1.186     brouard  11112:   /* Main ---------arguments file --------*/
1.126     brouard  11113: 
                   11114:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11115:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11116:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11117:     fflush(ficlog);
1.149     brouard  11118:     /* goto end; */
                   11119:     exit(70); 
1.126     brouard  11120:   }
                   11121: 
                   11122:   strcpy(filereso,"o");
1.201     brouard  11123:   strcat(filereso,fileresu);
1.126     brouard  11124:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11125:     printf("Problem with Output resultfile: %s\n", filereso);
                   11126:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11127:     fflush(ficlog);
                   11128:     goto end;
                   11129:   }
1.278     brouard  11130:       /*-------- Rewriting parameter file ----------*/
                   11131:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11132:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11133:   strcat(rfileres,".");    /* */
                   11134:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11135:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11136:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11137:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11138:     fflush(ficlog);
                   11139:     goto end;
                   11140:   }
                   11141:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11142: 
1.278     brouard  11143:                                      
1.126     brouard  11144:   /* Reads comments: lines beginning with '#' */
                   11145:   numlinepar=0;
1.277     brouard  11146:   /* Is it a BOM UTF-8 Windows file? */
                   11147:   /* First parameter line */
1.197     brouard  11148:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11149:     noffset=0;
                   11150:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11151:     {
                   11152:       noffset=noffset+3;
                   11153:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11154:     }
1.302     brouard  11155: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11156:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11157:     {
                   11158:       noffset=noffset+2;
                   11159:       printf("# File is an UTF16BE BOM file\n");
                   11160:     }
                   11161:     else if( line[0] == 0 && line[1] == 0)
                   11162:     {
                   11163:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11164:        noffset=noffset+4;
                   11165:        printf("# File is an UTF16BE BOM file\n");
                   11166:       }
                   11167:     } else{
                   11168:       ;/*printf(" Not a BOM file\n");*/
                   11169:     }
                   11170:   
1.197     brouard  11171:     /* If line starts with a # it is a comment */
1.277     brouard  11172:     if (line[noffset] == '#') {
1.197     brouard  11173:       numlinepar++;
                   11174:       fputs(line,stdout);
                   11175:       fputs(line,ficparo);
1.278     brouard  11176:       fputs(line,ficres);
1.197     brouard  11177:       fputs(line,ficlog);
                   11178:       continue;
                   11179:     }else
                   11180:       break;
                   11181:   }
                   11182:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11183:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11184:     if (num_filled != 5) {
                   11185:       printf("Should be 5 parameters\n");
1.283     brouard  11186:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11187:     }
1.126     brouard  11188:     numlinepar++;
1.197     brouard  11189:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11190:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11191:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11192:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11193:   }
                   11194:   /* Second parameter line */
                   11195:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11196:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11197:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11198:     if (line[0] == '#') {
                   11199:       numlinepar++;
1.283     brouard  11200:       printf("%s",line);
                   11201:       fprintf(ficres,"%s",line);
                   11202:       fprintf(ficparo,"%s",line);
                   11203:       fprintf(ficlog,"%s",line);
1.197     brouard  11204:       continue;
                   11205:     }else
                   11206:       break;
                   11207:   }
1.223     brouard  11208:   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", \
                   11209:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11210:     if (num_filled != 11) {
                   11211:       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  11212:       printf("but line=%s\n",line);
1.283     brouard  11213:       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");
                   11214:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11215:     }
1.286     brouard  11216:     if( lastpass > maxwav){
                   11217:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11218:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11219:       fflush(ficlog);
                   11220:       goto end;
                   11221:     }
                   11222:       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  11223:     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  11224:     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  11225:     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  11226:   }
1.203     brouard  11227:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11228:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11229:   /* Third parameter line */
                   11230:   while(fgets(line, MAXLINE, ficpar)) {
                   11231:     /* If line starts with a # it is a comment */
                   11232:     if (line[0] == '#') {
                   11233:       numlinepar++;
1.283     brouard  11234:       printf("%s",line);
                   11235:       fprintf(ficres,"%s",line);
                   11236:       fprintf(ficparo,"%s",line);
                   11237:       fprintf(ficlog,"%s",line);
1.197     brouard  11238:       continue;
                   11239:     }else
                   11240:       break;
                   11241:   }
1.201     brouard  11242:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11243:     if (num_filled != 1){
1.302     brouard  11244:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11245:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11246:       model[0]='\0';
                   11247:       goto end;
                   11248:     }
                   11249:     else{
                   11250:       if (model[0]=='+'){
                   11251:        for(i=1; i<=strlen(model);i++)
                   11252:          modeltemp[i-1]=model[i];
1.201     brouard  11253:        strcpy(model,modeltemp); 
1.197     brouard  11254:       }
                   11255:     }
1.199     brouard  11256:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11257:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11258:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11259:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11260:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11261:   }
                   11262:   /* 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); */
                   11263:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11264:   /* 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  11265:   /* 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); */
                   11266:   /* 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  11267:   fflush(ficlog);
1.190     brouard  11268:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11269:   if(model[0]=='#'){
1.279     brouard  11270:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11271:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11272:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11273:     if(mle != -1){
1.279     brouard  11274:       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  11275:       exit(1);
                   11276:     }
                   11277:   }
1.126     brouard  11278:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11279:     ungetc(c,ficpar);
                   11280:     fgets(line, MAXLINE, ficpar);
                   11281:     numlinepar++;
1.195     brouard  11282:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11283:       z[0]=line[1];
                   11284:     }
                   11285:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11286:     fputs(line, stdout);
                   11287:     //puts(line);
1.126     brouard  11288:     fputs(line,ficparo);
                   11289:     fputs(line,ficlog);
                   11290:   }
                   11291:   ungetc(c,ficpar);
                   11292: 
                   11293:    
1.290     brouard  11294:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11295:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11296:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11297:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11298:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11299:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11300:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11301:   */
                   11302:   if (strlen(model)>1) 
1.187     brouard  11303:     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  11304:   else
1.187     brouard  11305:     ncovmodel=2; /* Constant and age */
1.133     brouard  11306:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11307:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11308:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11309:     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);
                   11310:     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);
                   11311:     fflush(stdout);
                   11312:     fclose (ficlog);
                   11313:     goto end;
                   11314:   }
1.126     brouard  11315:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11316:   delti=delti3[1][1];
                   11317:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11318:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11319: /* We could also provide initial parameters values giving by simple logistic regression 
                   11320:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11321:       /* for(i=1;i<nlstate;i++){ */
                   11322:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11323:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11324:       /* } */
1.126     brouard  11325:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11326:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11327:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11328:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11329:     fclose (ficparo);
                   11330:     fclose (ficlog);
                   11331:     goto end;
                   11332:     exit(0);
1.220     brouard  11333:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11334:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11335:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11336:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11337:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11338:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11339:     hess=matrix(1,npar,1,npar);
1.220     brouard  11340:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11341:     /* Read guessed parameters */
1.126     brouard  11342:     /* Reads comments: lines beginning with '#' */
                   11343:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11344:       ungetc(c,ficpar);
                   11345:       fgets(line, MAXLINE, ficpar);
                   11346:       numlinepar++;
1.141     brouard  11347:       fputs(line,stdout);
1.126     brouard  11348:       fputs(line,ficparo);
                   11349:       fputs(line,ficlog);
                   11350:     }
                   11351:     ungetc(c,ficpar);
                   11352:     
                   11353:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11354:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11355:     for(i=1; i <=nlstate; i++){
1.234     brouard  11356:       j=0;
1.126     brouard  11357:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11358:        if(jj==i) continue;
                   11359:        j++;
1.292     brouard  11360:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11361:          ungetc(c,ficpar);
                   11362:          fgets(line, MAXLINE, ficpar);
                   11363:          numlinepar++;
                   11364:          fputs(line,stdout);
                   11365:          fputs(line,ficparo);
                   11366:          fputs(line,ficlog);
                   11367:        }
                   11368:        ungetc(c,ficpar);
1.234     brouard  11369:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11370:        if ((i1 != i) || (j1 != jj)){
                   11371:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11372: It might be a problem of design; if ncovcol and the model are correct\n \
                   11373: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11374:          exit(1);
                   11375:        }
                   11376:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11377:        if(mle==1)
                   11378:          printf("%1d%1d",i,jj);
                   11379:        fprintf(ficlog,"%1d%1d",i,jj);
                   11380:        for(k=1; k<=ncovmodel;k++){
                   11381:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11382:          if(mle==1){
                   11383:            printf(" %lf",param[i][j][k]);
                   11384:            fprintf(ficlog," %lf",param[i][j][k]);
                   11385:          }
                   11386:          else
                   11387:            fprintf(ficlog," %lf",param[i][j][k]);
                   11388:          fprintf(ficparo," %lf",param[i][j][k]);
                   11389:        }
                   11390:        fscanf(ficpar,"\n");
                   11391:        numlinepar++;
                   11392:        if(mle==1)
                   11393:          printf("\n");
                   11394:        fprintf(ficlog,"\n");
                   11395:        fprintf(ficparo,"\n");
1.126     brouard  11396:       }
                   11397:     }  
                   11398:     fflush(ficlog);
1.234     brouard  11399:     
1.251     brouard  11400:     /* Reads parameters values */
1.126     brouard  11401:     p=param[1][1];
1.251     brouard  11402:     pstart=paramstart[1][1];
1.126     brouard  11403:     
                   11404:     /* Reads comments: lines beginning with '#' */
                   11405:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11406:       ungetc(c,ficpar);
                   11407:       fgets(line, MAXLINE, ficpar);
                   11408:       numlinepar++;
1.141     brouard  11409:       fputs(line,stdout);
1.126     brouard  11410:       fputs(line,ficparo);
                   11411:       fputs(line,ficlog);
                   11412:     }
                   11413:     ungetc(c,ficpar);
                   11414: 
                   11415:     for(i=1; i <=nlstate; i++){
                   11416:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11417:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11418:        if ( (i1-i) * (j1-j) != 0){
                   11419:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11420:          exit(1);
                   11421:        }
                   11422:        printf("%1d%1d",i,j);
                   11423:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11424:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11425:        for(k=1; k<=ncovmodel;k++){
                   11426:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11427:          printf(" %le",delti3[i][j][k]);
                   11428:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11429:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11430:        }
                   11431:        fscanf(ficpar,"\n");
                   11432:        numlinepar++;
                   11433:        printf("\n");
                   11434:        fprintf(ficparo,"\n");
                   11435:        fprintf(ficlog,"\n");
1.126     brouard  11436:       }
                   11437:     }
                   11438:     fflush(ficlog);
1.234     brouard  11439:     
1.145     brouard  11440:     /* Reads covariance matrix */
1.126     brouard  11441:     delti=delti3[1][1];
1.220     brouard  11442:                
                   11443:                
1.126     brouard  11444:     /* 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  11445:                
1.126     brouard  11446:     /* Reads comments: lines beginning with '#' */
                   11447:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11448:       ungetc(c,ficpar);
                   11449:       fgets(line, MAXLINE, ficpar);
                   11450:       numlinepar++;
1.141     brouard  11451:       fputs(line,stdout);
1.126     brouard  11452:       fputs(line,ficparo);
                   11453:       fputs(line,ficlog);
                   11454:     }
                   11455:     ungetc(c,ficpar);
1.220     brouard  11456:                
1.126     brouard  11457:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11458:     hess=matrix(1,npar,1,npar);
1.131     brouard  11459:     for(i=1; i <=npar; i++)
                   11460:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11461:                
1.194     brouard  11462:     /* Scans npar lines */
1.126     brouard  11463:     for(i=1; i <=npar; i++){
1.226     brouard  11464:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11465:       if(count != 3){
1.226     brouard  11466:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11467: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11468: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11469:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11470: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11471: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11472:        exit(1);
1.220     brouard  11473:       }else{
1.226     brouard  11474:        if(mle==1)
                   11475:          printf("%1d%1d%d",i1,j1,jk);
                   11476:       }
                   11477:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11478:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11479:       for(j=1; j <=i; j++){
1.226     brouard  11480:        fscanf(ficpar," %le",&matcov[i][j]);
                   11481:        if(mle==1){
                   11482:          printf(" %.5le",matcov[i][j]);
                   11483:        }
                   11484:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11485:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11486:       }
                   11487:       fscanf(ficpar,"\n");
                   11488:       numlinepar++;
                   11489:       if(mle==1)
1.220     brouard  11490:                                printf("\n");
1.126     brouard  11491:       fprintf(ficlog,"\n");
                   11492:       fprintf(ficparo,"\n");
                   11493:     }
1.194     brouard  11494:     /* End of read covariance matrix npar lines */
1.126     brouard  11495:     for(i=1; i <=npar; i++)
                   11496:       for(j=i+1;j<=npar;j++)
1.226     brouard  11497:        matcov[i][j]=matcov[j][i];
1.126     brouard  11498:     
                   11499:     if(mle==1)
                   11500:       printf("\n");
                   11501:     fprintf(ficlog,"\n");
                   11502:     
                   11503:     fflush(ficlog);
                   11504:     
                   11505:   }    /* End of mle != -3 */
1.218     brouard  11506:   
1.186     brouard  11507:   /*  Main data
                   11508:    */
1.290     brouard  11509:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11510:   /* num=lvector(1,n); */
                   11511:   /* moisnais=vector(1,n); */
                   11512:   /* annais=vector(1,n); */
                   11513:   /* moisdc=vector(1,n); */
                   11514:   /* andc=vector(1,n); */
                   11515:   /* weight=vector(1,n); */
                   11516:   /* agedc=vector(1,n); */
                   11517:   /* cod=ivector(1,n); */
                   11518:   /* for(i=1;i<=n;i++){ */
                   11519:   num=lvector(firstobs,lastobs);
                   11520:   moisnais=vector(firstobs,lastobs);
                   11521:   annais=vector(firstobs,lastobs);
                   11522:   moisdc=vector(firstobs,lastobs);
                   11523:   andc=vector(firstobs,lastobs);
                   11524:   weight=vector(firstobs,lastobs);
                   11525:   agedc=vector(firstobs,lastobs);
                   11526:   cod=ivector(firstobs,lastobs);
                   11527:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11528:     num[i]=0;
                   11529:     moisnais[i]=0;
                   11530:     annais[i]=0;
                   11531:     moisdc[i]=0;
                   11532:     andc[i]=0;
                   11533:     agedc[i]=0;
                   11534:     cod[i]=0;
                   11535:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11536:   }
1.290     brouard  11537:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11538:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11539:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11540:   tab=ivector(1,NCOVMAX);
1.144     brouard  11541:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11542:   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  11543: 
1.136     brouard  11544:   /* Reads data from file datafile */
                   11545:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11546:     goto end;
                   11547: 
                   11548:   /* Calculation of the number of parameters from char model */
1.234     brouard  11549:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11550:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11551:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11552:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11553:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11554:   */
                   11555:   
                   11556:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11557:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11558:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11559:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11560:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11561:   TvarF=ivector(1,NCOVMAX); /*  */
                   11562:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11563:   TvarV=ivector(1,NCOVMAX); /*  */
                   11564:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11565:   TvarA=ivector(1,NCOVMAX); /*  */
                   11566:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11567:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11568:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11569:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11570:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11571:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11572:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11573:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11574:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11575: 
1.230     brouard  11576:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11577:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11578:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11579:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11580:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11581:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11582:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11583:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11584:   */
                   11585:   /* For model-covariate k tells which data-covariate to use but
                   11586:     because this model-covariate is a construction we invent a new column
                   11587:     ncovcol + k1
                   11588:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11589:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11590:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11591:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11592:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11593:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11594:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11595:   */
1.145     brouard  11596:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11597:   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  11598:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11599:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11600:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11601:                         4 covariates (3 plus signs)
                   11602:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11603:                      */  
1.230     brouard  11604:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11605:                                * individual dummy, fixed or varying:
                   11606:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11607:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11608:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11609:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11610:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11611:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11612:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11613:                                * individual quantitative, fixed or varying:
                   11614:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11615:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11616:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11617: /* Main decodemodel */
                   11618: 
1.187     brouard  11619: 
1.223     brouard  11620:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11621:     goto end;
                   11622: 
1.137     brouard  11623:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11624:     nbwarn++;
                   11625:     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); 
                   11626:     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); 
                   11627:   }
1.136     brouard  11628:     /*  if(mle==1){*/
1.137     brouard  11629:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11630:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11631:   }
                   11632: 
                   11633:     /*-calculation of age at interview from date of interview and age at death -*/
                   11634:   agev=matrix(1,maxwav,1,imx);
                   11635: 
                   11636:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11637:     goto end;
                   11638: 
1.126     brouard  11639: 
1.136     brouard  11640:   agegomp=(int)agemin;
1.290     brouard  11641:   free_vector(moisnais,firstobs,lastobs);
                   11642:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11643:   /* free_matrix(mint,1,maxwav,1,n);
                   11644:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11645:   /* free_vector(moisdc,1,n); */
                   11646:   /* free_vector(andc,1,n); */
1.145     brouard  11647:   /* */
                   11648:   
1.126     brouard  11649:   wav=ivector(1,imx);
1.214     brouard  11650:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11651:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11652:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11653:   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.*/
                   11654:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11655:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11656:    
                   11657:   /* Concatenates waves */
1.214     brouard  11658:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11659:      Death is a valid wave (if date is known).
                   11660:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11661:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11662:      and mw[mi+1][i]. dh depends on stepm.
                   11663:   */
                   11664: 
1.126     brouard  11665:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11666:   /* Concatenates waves */
1.145     brouard  11667:  
1.290     brouard  11668:   free_vector(moisdc,firstobs,lastobs);
                   11669:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11670: 
1.126     brouard  11671:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11672:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11673:   ncodemax[1]=1;
1.145     brouard  11674:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11675:   cptcoveff=0;
1.220     brouard  11676:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11677:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11678:   }
                   11679:   
                   11680:   ncovcombmax=pow(2,cptcoveff);
                   11681:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11682:   for(i=1;i<ncovcombmax;i++)
                   11683:     invalidvarcomb[i]=0;
                   11684:   
1.211     brouard  11685:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11686:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11687:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11688:   
1.200     brouard  11689:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11690:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11691:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11692:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11693:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11694:    * (currently 0 or 1) in the data.
                   11695:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11696:    * corresponding modality (h,j).
                   11697:    */
                   11698: 
1.145     brouard  11699:   h=0;
                   11700:   /*if (cptcovn > 0) */
1.126     brouard  11701:   m=pow(2,cptcoveff);
                   11702:  
1.144     brouard  11703:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11704:           * For k=4 covariates, h goes from 1 to m=2**k
                   11705:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11706:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11707:           *     h\k   1     2     3     4
1.143     brouard  11708:           *______________________________  
                   11709:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11710:           *     2     2     1     1     1
                   11711:           *     3 i=2 1     2     1     1
                   11712:           *     4     2     2     1     1
                   11713:           *     5 i=3 1 i=2 1     2     1
                   11714:           *     6     2     1     2     1
                   11715:           *     7 i=4 1     2     2     1
                   11716:           *     8     2     2     2     1
1.197     brouard  11717:           *     9 i=5 1 i=3 1 i=2 1     2
                   11718:           *    10     2     1     1     2
                   11719:           *    11 i=6 1     2     1     2
                   11720:           *    12     2     2     1     2
                   11721:           *    13 i=7 1 i=4 1     2     2    
                   11722:           *    14     2     1     2     2
                   11723:           *    15 i=8 1     2     2     2
                   11724:           *    16     2     2     2     2
1.143     brouard  11725:           */
1.212     brouard  11726:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11727:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11728:      * and the value of each covariate?
                   11729:      * V1=1, V2=1, V3=2, V4=1 ?
                   11730:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11731:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11732:      * In order to get the real value in the data, we use nbcode
                   11733:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11734:      * We are keeping this crazy system in order to be able (in the future?) 
                   11735:      * to have more than 2 values (0 or 1) for a covariate.
                   11736:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11737:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11738:      *              bbbbbbbb
                   11739:      *              76543210     
                   11740:      *   h-1        00000101 (6-1=5)
1.219     brouard  11741:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11742:      *           &
                   11743:      *     1        00000001 (1)
1.219     brouard  11744:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11745:      *          +1= 00000001 =1 
1.211     brouard  11746:      *
                   11747:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11748:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11749:      *    >>k'            11
                   11750:      *          &   00000001
                   11751:      *            = 00000001
                   11752:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11753:      * Reverse h=6 and m=16?
                   11754:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11755:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11756:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11757:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11758:      * V3=decodtabm(14,3,2**4)=2
                   11759:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11760:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11761:      *          &1 000000001
                   11762:      *           = 000000001
                   11763:      *         +1= 000000010 =2
                   11764:      *                  2211
                   11765:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11766:      *                  V3=2
1.220     brouard  11767:                 * codtabm and decodtabm are identical
1.211     brouard  11768:      */
                   11769: 
1.145     brouard  11770: 
                   11771:  free_ivector(Ndum,-1,NCOVMAX);
                   11772: 
                   11773: 
1.126     brouard  11774:     
1.186     brouard  11775:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11776:   strcpy(optionfilegnuplot,optionfilefiname);
                   11777:   if(mle==-3)
1.201     brouard  11778:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11779:   strcat(optionfilegnuplot,".gp");
                   11780: 
                   11781:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11782:     printf("Problem with file %s",optionfilegnuplot);
                   11783:   }
                   11784:   else{
1.204     brouard  11785:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11786:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11787:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11788:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11789:   }
                   11790:   /*  fclose(ficgp);*/
1.186     brouard  11791: 
                   11792: 
                   11793:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11794: 
                   11795:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11796:   if(mle==-3)
1.201     brouard  11797:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11798:   strcat(optionfilehtm,".htm");
                   11799:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11800:     printf("Problem with %s \n",optionfilehtm);
                   11801:     exit(0);
1.126     brouard  11802:   }
                   11803: 
                   11804:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11805:   strcat(optionfilehtmcov,"-cov.htm");
                   11806:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11807:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11808:   }
                   11809:   else{
                   11810:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11811: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11812: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11813:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11814:   }
                   11815: 
1.213     brouard  11816:   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  11817: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11818: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11819: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11820: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11821: \n\
                   11822: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11823:  <ul><li><h4>Parameter files</h4>\n\
                   11824:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11825:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11826:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11827:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11828:  - Date and time at start: %s</ul>\n",\
                   11829:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11830:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11831:          fileres,fileres,\
                   11832:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11833:   fflush(fichtm);
                   11834: 
                   11835:   strcpy(pathr,path);
                   11836:   strcat(pathr,optionfilefiname);
1.184     brouard  11837: #ifdef WIN32
                   11838:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11839: #else
1.126     brouard  11840:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11841: #endif
                   11842:          
1.126     brouard  11843:   
1.220     brouard  11844:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11845:                 and for any valid combination of covariates
1.126     brouard  11846:      and prints on file fileres'p'. */
1.251     brouard  11847:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11848:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11849: 
                   11850:   fprintf(fichtm,"\n");
1.286     brouard  11851:   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  11852:          ftol, stepm);
                   11853:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11854:   ncurrv=1;
                   11855:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11856:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11857:   ncurrv=i;
                   11858:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11859:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11860:   ncurrv=i;
                   11861:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11862:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11863:   ncurrv=i;
                   11864:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11865:   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", \
                   11866:           nlstate, ndeath, maxwav, mle, weightopt);
                   11867: 
                   11868:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11869: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11870: 
                   11871:   
                   11872:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11873: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11874: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11875:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11876:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11877:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11878:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11879:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11880:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11881: 
1.126     brouard  11882:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11883:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11884:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11885: 
                   11886:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11887:   /* For mortality only */
1.126     brouard  11888:   if (mle==-3){
1.136     brouard  11889:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11890:     for(i=1;i<=NDIM;i++)
                   11891:       for(j=1;j<=NDIM;j++)
                   11892:        ximort[i][j]=0.;
1.186     brouard  11893:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11894:     cens=ivector(firstobs,lastobs);
                   11895:     ageexmed=vector(firstobs,lastobs);
                   11896:     agecens=vector(firstobs,lastobs);
                   11897:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11898:                
1.126     brouard  11899:     for (i=1; i<=imx; i++){
                   11900:       dcwave[i]=-1;
                   11901:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11902:        if (s[m][i]>nlstate) {
                   11903:          dcwave[i]=m;
                   11904:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11905:          break;
                   11906:        }
1.126     brouard  11907:     }
1.226     brouard  11908:     
1.126     brouard  11909:     for (i=1; i<=imx; i++) {
                   11910:       if (wav[i]>0){
1.226     brouard  11911:        ageexmed[i]=agev[mw[1][i]][i];
                   11912:        j=wav[i];
                   11913:        agecens[i]=1.; 
                   11914:        
                   11915:        if (ageexmed[i]> 1 && wav[i] > 0){
                   11916:          agecens[i]=agev[mw[j][i]][i];
                   11917:          cens[i]= 1;
                   11918:        }else if (ageexmed[i]< 1) 
                   11919:          cens[i]= -1;
                   11920:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   11921:          cens[i]=0 ;
1.126     brouard  11922:       }
                   11923:       else cens[i]=-1;
                   11924:     }
                   11925:     
                   11926:     for (i=1;i<=NDIM;i++) {
                   11927:       for (j=1;j<=NDIM;j++)
1.226     brouard  11928:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  11929:     }
                   11930:     
1.302     brouard  11931:     p[1]=0.0268; p[NDIM]=0.083;
                   11932:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  11933:     
                   11934:     
1.136     brouard  11935: #ifdef GSL
                   11936:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  11937: #else
1.126     brouard  11938:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  11939: #endif
1.201     brouard  11940:     strcpy(filerespow,"POW-MORT_"); 
                   11941:     strcat(filerespow,fileresu);
1.126     brouard  11942:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   11943:       printf("Problem with resultfile: %s\n", filerespow);
                   11944:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   11945:     }
1.136     brouard  11946: #ifdef GSL
                   11947:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  11948: #else
1.126     brouard  11949:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  11950: #endif
1.126     brouard  11951:     /*  for (i=1;i<=nlstate;i++)
                   11952:        for(j=1;j<=nlstate+ndeath;j++)
                   11953:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   11954:     */
                   11955:     fprintf(ficrespow,"\n");
1.136     brouard  11956: #ifdef GSL
                   11957:     /* gsl starts here */ 
                   11958:     T = gsl_multimin_fminimizer_nmsimplex;
                   11959:     gsl_multimin_fminimizer *sfm = NULL;
                   11960:     gsl_vector *ss, *x;
                   11961:     gsl_multimin_function minex_func;
                   11962: 
                   11963:     /* Initial vertex size vector */
                   11964:     ss = gsl_vector_alloc (NDIM);
                   11965:     
                   11966:     if (ss == NULL){
                   11967:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   11968:     }
                   11969:     /* Set all step sizes to 1 */
                   11970:     gsl_vector_set_all (ss, 0.001);
                   11971: 
                   11972:     /* Starting point */
1.126     brouard  11973:     
1.136     brouard  11974:     x = gsl_vector_alloc (NDIM);
                   11975:     
                   11976:     if (x == NULL){
                   11977:       gsl_vector_free(ss);
                   11978:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   11979:     }
                   11980:   
                   11981:     /* Initialize method and iterate */
                   11982:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  11983:     /*     gsl_vector_set(x, 0, 0.0268); */
                   11984:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  11985:     gsl_vector_set(x, 0, p[1]);
                   11986:     gsl_vector_set(x, 1, p[2]);
                   11987: 
                   11988:     minex_func.f = &gompertz_f;
                   11989:     minex_func.n = NDIM;
                   11990:     minex_func.params = (void *)&p; /* ??? */
                   11991:     
                   11992:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   11993:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   11994:     
                   11995:     printf("Iterations beginning .....\n\n");
                   11996:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   11997: 
                   11998:     iteri=0;
                   11999:     while (rval == GSL_CONTINUE){
                   12000:       iteri++;
                   12001:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12002:       
                   12003:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12004:       fflush(0);
                   12005:       
                   12006:       if (status) 
                   12007:         break;
                   12008:       
                   12009:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12010:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12011:       
                   12012:       if (rval == GSL_SUCCESS)
                   12013:         printf ("converged to a local maximum at\n");
                   12014:       
                   12015:       printf("%5d ", iteri);
                   12016:       for (it = 0; it < NDIM; it++){
                   12017:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12018:       }
                   12019:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12020:     }
                   12021:     
                   12022:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12023:     
                   12024:     gsl_vector_free(x); /* initial values */
                   12025:     gsl_vector_free(ss); /* inital step size */
                   12026:     for (it=0; it<NDIM; it++){
                   12027:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12028:       fprintf(ficrespow," %.12lf", p[it]);
                   12029:     }
                   12030:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12031: #endif
                   12032: #ifdef POWELL
                   12033:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12034: #endif  
1.126     brouard  12035:     fclose(ficrespow);
                   12036:     
1.203     brouard  12037:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12038: 
                   12039:     for(i=1; i <=NDIM; i++)
                   12040:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12041:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12042:     
                   12043:     printf("\nCovariance matrix\n ");
1.203     brouard  12044:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12045:     for(i=1; i <=NDIM; i++) {
                   12046:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12047:                                printf("%f ",matcov[i][j]);
                   12048:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12049:       }
1.203     brouard  12050:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12051:     }
                   12052:     
                   12053:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12054:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12055:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12056:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12057:     }
1.302     brouard  12058:     lsurv=vector(agegomp,AGESUP);
                   12059:     lpop=vector(agegomp,AGESUP);
                   12060:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12061:     lsurv[agegomp]=100000;
                   12062:     
                   12063:     for (k=agegomp;k<=AGESUP;k++) {
                   12064:       agemortsup=k;
                   12065:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12066:     }
                   12067:     
                   12068:     for (k=agegomp;k<agemortsup;k++)
                   12069:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12070:     
                   12071:     for (k=agegomp;k<agemortsup;k++){
                   12072:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12073:       sumlpop=sumlpop+lpop[k];
                   12074:     }
                   12075:     
                   12076:     tpop[agegomp]=sumlpop;
                   12077:     for (k=agegomp;k<(agemortsup-3);k++){
                   12078:       /*  tpop[k+1]=2;*/
                   12079:       tpop[k+1]=tpop[k]-lpop[k];
                   12080:     }
                   12081:     
                   12082:     
                   12083:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12084:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12085:       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]);
                   12086:     
                   12087:     
                   12088:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12089:                ageminpar=50;
                   12090:                agemaxpar=100;
1.194     brouard  12091:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12092:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12093: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12094: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12095:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12096: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12097: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12098:     }else{
                   12099:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12100:                        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  12101:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12102:                }
1.201     brouard  12103:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12104:                     stepm, weightopt,\
                   12105:                     model,imx,p,matcov,agemortsup);
                   12106:     
1.302     brouard  12107:     free_vector(lsurv,agegomp,AGESUP);
                   12108:     free_vector(lpop,agegomp,AGESUP);
                   12109:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12110:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12111:     free_ivector(dcwave,firstobs,lastobs);
                   12112:     free_vector(agecens,firstobs,lastobs);
                   12113:     free_vector(ageexmed,firstobs,lastobs);
                   12114:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12115: #ifdef GSL
1.136     brouard  12116: #endif
1.186     brouard  12117:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12118:   /* Standard  */
                   12119:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12120:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12121:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12122:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12123:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12124:     for (k=1; k<=npar;k++)
                   12125:       printf(" %d %8.5f",k,p[k]);
                   12126:     printf("\n");
1.205     brouard  12127:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12128:       /* mlikeli uses func not funcone */
1.247     brouard  12129:       /* for(i=1;i<nlstate;i++){ */
                   12130:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12131:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12132:       /* } */
1.205     brouard  12133:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12134:     }
                   12135:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12136:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12137:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12138:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12139:     }
                   12140:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12141:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12142:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12143:     for (k=1; k<=npar;k++)
                   12144:       printf(" %d %8.5f",k,p[k]);
                   12145:     printf("\n");
                   12146:     
                   12147:     /*--------- results files --------------*/
1.283     brouard  12148:     /* 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  12149:     
                   12150:     
                   12151:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12152:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12153:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12154:     for(i=1,jk=1; i <=nlstate; i++){
                   12155:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12156:        if (k != i) {
                   12157:          printf("%d%d ",i,k);
                   12158:          fprintf(ficlog,"%d%d ",i,k);
                   12159:          fprintf(ficres,"%1d%1d ",i,k);
                   12160:          for(j=1; j <=ncovmodel; j++){
                   12161:            printf("%12.7f ",p[jk]);
                   12162:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12163:            fprintf(ficres,"%12.7f ",p[jk]);
                   12164:            jk++; 
                   12165:          }
                   12166:          printf("\n");
                   12167:          fprintf(ficlog,"\n");
                   12168:          fprintf(ficres,"\n");
                   12169:        }
1.126     brouard  12170:       }
                   12171:     }
1.203     brouard  12172:     if(mle != 0){
                   12173:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12174:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12175:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12176:       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");
                   12177:       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");
                   12178:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12179:        for(k=1; k <=(nlstate+ndeath); k++){
                   12180:          if (k != i) {
                   12181:            printf("%d%d ",i,k);
                   12182:            fprintf(ficlog,"%d%d ",i,k);
                   12183:            for(j=1; j <=ncovmodel; j++){
                   12184:              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]));
                   12185:              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]));
                   12186:              jk++; 
                   12187:            }
                   12188:            printf("\n");
                   12189:            fprintf(ficlog,"\n");
                   12190:          }
                   12191:        }
1.193     brouard  12192:       }
1.203     brouard  12193:     } /* end of hesscov and Wald tests */
1.225     brouard  12194:     
1.203     brouard  12195:     /*  */
1.126     brouard  12196:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12197:     printf("# Scales (for hessian or gradient estimation)\n");
                   12198:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12199:     for(i=1,jk=1; i <=nlstate; i++){
                   12200:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12201:        if (j!=i) {
                   12202:          fprintf(ficres,"%1d%1d",i,j);
                   12203:          printf("%1d%1d",i,j);
                   12204:          fprintf(ficlog,"%1d%1d",i,j);
                   12205:          for(k=1; k<=ncovmodel;k++){
                   12206:            printf(" %.5e",delti[jk]);
                   12207:            fprintf(ficlog," %.5e",delti[jk]);
                   12208:            fprintf(ficres," %.5e",delti[jk]);
                   12209:            jk++;
                   12210:          }
                   12211:          printf("\n");
                   12212:          fprintf(ficlog,"\n");
                   12213:          fprintf(ficres,"\n");
                   12214:        }
1.126     brouard  12215:       }
                   12216:     }
                   12217:     
                   12218:     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  12219:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12220:       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");
                   12221:     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");
                   12222:     /* # 121 Var(a12)\n\ */
                   12223:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12224:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12225:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12226:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12227:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12228:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12229:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12230:     
                   12231:     
                   12232:     /* Just to have a covariance matrix which will be more understandable
                   12233:        even is we still don't want to manage dictionary of variables
                   12234:     */
                   12235:     for(itimes=1;itimes<=2;itimes++){
                   12236:       jj=0;
                   12237:       for(i=1; i <=nlstate; i++){
1.225     brouard  12238:        for(j=1; j <=nlstate+ndeath; j++){
                   12239:          if(j==i) continue;
                   12240:          for(k=1; k<=ncovmodel;k++){
                   12241:            jj++;
                   12242:            ca[0]= k+'a'-1;ca[1]='\0';
                   12243:            if(itimes==1){
                   12244:              if(mle>=1)
                   12245:                printf("#%1d%1d%d",i,j,k);
                   12246:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12247:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12248:            }else{
                   12249:              if(mle>=1)
                   12250:                printf("%1d%1d%d",i,j,k);
                   12251:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12252:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12253:            }
                   12254:            ll=0;
                   12255:            for(li=1;li <=nlstate; li++){
                   12256:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12257:                if(lj==li) continue;
                   12258:                for(lk=1;lk<=ncovmodel;lk++){
                   12259:                  ll++;
                   12260:                  if(ll<=jj){
                   12261:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12262:                    if(ll<jj){
                   12263:                      if(itimes==1){
                   12264:                        if(mle>=1)
                   12265:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12266:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12267:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12268:                      }else{
                   12269:                        if(mle>=1)
                   12270:                          printf(" %.5e",matcov[jj][ll]); 
                   12271:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12272:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12273:                      }
                   12274:                    }else{
                   12275:                      if(itimes==1){
                   12276:                        if(mle>=1)
                   12277:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12278:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12279:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12280:                      }else{
                   12281:                        if(mle>=1)
                   12282:                          printf(" %.7e",matcov[jj][ll]); 
                   12283:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12284:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12285:                      }
                   12286:                    }
                   12287:                  }
                   12288:                } /* end lk */
                   12289:              } /* end lj */
                   12290:            } /* end li */
                   12291:            if(mle>=1)
                   12292:              printf("\n");
                   12293:            fprintf(ficlog,"\n");
                   12294:            fprintf(ficres,"\n");
                   12295:            numlinepar++;
                   12296:          } /* end k*/
                   12297:        } /*end j */
1.126     brouard  12298:       } /* end i */
                   12299:     } /* end itimes */
                   12300:     
                   12301:     fflush(ficlog);
                   12302:     fflush(ficres);
1.225     brouard  12303:     while(fgets(line, MAXLINE, ficpar)) {
                   12304:       /* If line starts with a # it is a comment */
                   12305:       if (line[0] == '#') {
                   12306:        numlinepar++;
                   12307:        fputs(line,stdout);
                   12308:        fputs(line,ficparo);
                   12309:        fputs(line,ficlog);
1.299     brouard  12310:        fputs(line,ficres);
1.225     brouard  12311:        continue;
                   12312:       }else
                   12313:        break;
                   12314:     }
                   12315:     
1.209     brouard  12316:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12317:     /*   ungetc(c,ficpar); */
                   12318:     /*   fgets(line, MAXLINE, ficpar); */
                   12319:     /*   fputs(line,stdout); */
                   12320:     /*   fputs(line,ficparo); */
                   12321:     /* } */
                   12322:     /* ungetc(c,ficpar); */
1.126     brouard  12323:     
                   12324:     estepm=0;
1.209     brouard  12325:     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  12326:       
                   12327:       if (num_filled != 6) {
                   12328:        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);
                   12329:        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);
                   12330:        goto end;
                   12331:       }
                   12332:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12333:     }
                   12334:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12335:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12336:     
1.209     brouard  12337:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12338:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12339:     if (fage <= 2) {
                   12340:       bage = ageminpar;
                   12341:       fage = agemaxpar;
                   12342:     }
                   12343:     
                   12344:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12345:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12346:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12347:                
1.186     brouard  12348:     /* Other stuffs, more or less useful */    
1.254     brouard  12349:     while(fgets(line, MAXLINE, ficpar)) {
                   12350:       /* If line starts with a # it is a comment */
                   12351:       if (line[0] == '#') {
                   12352:        numlinepar++;
                   12353:        fputs(line,stdout);
                   12354:        fputs(line,ficparo);
                   12355:        fputs(line,ficlog);
1.299     brouard  12356:        fputs(line,ficres);
1.254     brouard  12357:        continue;
                   12358:       }else
                   12359:        break;
                   12360:     }
                   12361: 
                   12362:     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){
                   12363:       
                   12364:       if (num_filled != 7) {
                   12365:        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);
                   12366:        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);
                   12367:        goto end;
                   12368:       }
                   12369:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12370:       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);
                   12371:       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);
                   12372:       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  12373:     }
1.254     brouard  12374: 
                   12375:     while(fgets(line, MAXLINE, ficpar)) {
                   12376:       /* If line starts with a # it is a comment */
                   12377:       if (line[0] == '#') {
                   12378:        numlinepar++;
                   12379:        fputs(line,stdout);
                   12380:        fputs(line,ficparo);
                   12381:        fputs(line,ficlog);
1.299     brouard  12382:        fputs(line,ficres);
1.254     brouard  12383:        continue;
                   12384:       }else
                   12385:        break;
1.126     brouard  12386:     }
                   12387:     
                   12388:     
                   12389:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12390:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12391:     
1.254     brouard  12392:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12393:       if (num_filled != 1) {
                   12394:        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);
                   12395:        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);
                   12396:        goto end;
                   12397:       }
                   12398:       printf("pop_based=%d\n",popbased);
                   12399:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12400:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12401:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12402:     }
                   12403:      
1.258     brouard  12404:     /* Results */
                   12405:     nresult=0;
                   12406:     do{
                   12407:       if(!fgets(line, MAXLINE, ficpar)){
                   12408:        endishere=1;
                   12409:        parameterline=14;
                   12410:       }else if (line[0] == '#') {
                   12411:        /* If line starts with a # it is a comment */
1.254     brouard  12412:        numlinepar++;
                   12413:        fputs(line,stdout);
                   12414:        fputs(line,ficparo);
                   12415:        fputs(line,ficlog);
1.299     brouard  12416:        fputs(line,ficres);
1.254     brouard  12417:        continue;
1.258     brouard  12418:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12419:        parameterline=11;
1.296     brouard  12420:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12421:        parameterline=12;
                   12422:       else if(sscanf(line,"result:%[^\n]\n",modeltemp))
                   12423:        parameterline=13;
                   12424:       else{
                   12425:        parameterline=14;
1.254     brouard  12426:       }
1.258     brouard  12427:       switch (parameterline){ 
                   12428:       case 11:
1.296     brouard  12429:        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)){
                   12430:                  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  12431:          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);
                   12432:          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);
                   12433:          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);
                   12434:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12435:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12436:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12437:           prvforecast = 1;
                   12438:        } 
                   12439:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.302     brouard  12440:          printf("prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12441:          fprintf(ficlog,"prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12442:          fprintf(ficres,"prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12443:           prvforecast = 2;
                   12444:        }
                   12445:        else {
                   12446:          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);
                   12447:          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);
                   12448:          goto end;
1.258     brouard  12449:        }
1.254     brouard  12450:        break;
1.258     brouard  12451:       case 12:
1.296     brouard  12452:        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)){
                   12453:           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);
                   12454:          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);
                   12455:          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);
                   12456:          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);
                   12457:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12458:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12459:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12460:           prvbackcast = 1;
                   12461:        } 
                   12462:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.302     brouard  12463:          printf("prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12464:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12465:          fprintf(ficres,"prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12466:           prvbackcast = 2;
                   12467:        }
                   12468:        else {
                   12469:          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);
                   12470:          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);
                   12471:          goto end;
1.258     brouard  12472:        }
1.230     brouard  12473:        break;
1.258     brouard  12474:       case 13:
                   12475:        if((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   12476:          if (num_filled == 0){
                   12477:            resultline[0]='\0';
                   12478:            printf("Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   12479:            fprintf(ficlog,"Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   12480:            break;
                   12481:          } else if (num_filled != 1){
                   12482:            printf("ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12483:            fprintf(ficlog,"ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12484:          }
                   12485:          nresult++; /* Sum of resultlines */
                   12486:          printf("Result %d: result=%s\n",nresult, resultline);
                   12487:          if(nresult > MAXRESULTLINES){
                   12488:            printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12489:            fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12490:            goto end;
                   12491:          }
                   12492:          decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   12493:          fprintf(ficparo,"result: %s\n",resultline);
                   12494:          fprintf(ficres,"result: %s\n",resultline);
                   12495:          fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  12496:          break;
1.303   ! brouard  12497:        case 14:
        !          12498:          printf("Error: Unknown command '%s'\n",line);
        !          12499:          fprintf(ficlog,"Error: Unknown command '%s'\n",line);
        !          12500:          if(ncovmodel >=2 && nresult==0 ){
1.259     brouard  12501:            printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.303   ! brouard  12502:            fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12503:          }
1.303   ! brouard  12504:          goto end;
1.259     brouard  12505:          break;
1.258     brouard  12506:        default:
                   12507:          nresult=1;
                   12508:          decoderesult(".",nresult ); /* No covariate */
                   12509:        }
                   12510:       } /* End switch parameterline */
                   12511:     }while(endishere==0); /* End do */
1.126     brouard  12512:     
1.230     brouard  12513:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12514:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12515:     
                   12516:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12517:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12518:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12519: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12520: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12521:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12522: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12523: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12524:     }else{
1.270     brouard  12525:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12526:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12527:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12528:       if(prvforecast==1){
                   12529:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12530:         jprojd=jproj1;
                   12531:         mprojd=mproj1;
                   12532:         anprojd=anproj1;
                   12533:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12534:         jprojf=jproj2;
                   12535:         mprojf=mproj2;
                   12536:         anprojf=anproj2;
                   12537:       } else if(prvforecast == 2){
                   12538:         dateprojd=dateintmean;
                   12539:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12540:         dateprojf=dateintmean+yrfproj;
                   12541:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12542:       }
                   12543:       if(prvbackcast==1){
                   12544:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12545:         jbackd=jback1;
                   12546:         mbackd=mback1;
                   12547:         anbackd=anback1;
                   12548:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12549:         jbackf=jback2;
                   12550:         mbackf=mback2;
                   12551:         anbackf=anback2;
                   12552:       } else if(prvbackcast == 2){
                   12553:         datebackd=dateintmean;
                   12554:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12555:         datebackf=dateintmean-yrbproj;
                   12556:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12557:       }
                   12558:       
                   12559:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12560:     }
                   12561:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12562:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12563:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12564:                
1.225     brouard  12565:     /*------------ free_vector  -------------*/
                   12566:     /*  chdir(path); */
1.220     brouard  12567:                
1.215     brouard  12568:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12569:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12570:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12571:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12572:     free_lvector(num,firstobs,lastobs);
                   12573:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12574:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12575:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12576:     fclose(ficparo);
                   12577:     fclose(ficres);
1.220     brouard  12578:                
                   12579:                
1.186     brouard  12580:     /* Other results (useful)*/
1.220     brouard  12581:                
                   12582:                
1.126     brouard  12583:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12584:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12585:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12586:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12587:     fclose(ficrespl);
                   12588: 
                   12589:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12590:     /*#include "hpijx.h"*/
                   12591:     hPijx(p, bage, fage);
1.145     brouard  12592:     fclose(ficrespij);
1.227     brouard  12593:     
1.220     brouard  12594:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12595:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12596:     k=1;
1.126     brouard  12597:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12598:     
1.269     brouard  12599:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12600:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12601:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12602:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12603:        for(k=1;k<=ncovcombmax;k++)
                   12604:          probs[i][j][k]=0.;
1.269     brouard  12605:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12606:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12607:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12608:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12609:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12610:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12611:          for(k=1;k<=ncovcombmax;k++)
                   12612:            mobaverages[i][j][k]=0.;
1.219     brouard  12613:       mobaverage=mobaverages;
                   12614:       if (mobilav!=0) {
1.235     brouard  12615:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12616:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12617:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12618:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12619:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12620:        }
1.269     brouard  12621:       } else if (mobilavproj !=0) {
1.235     brouard  12622:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12623:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12624:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12625:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12626:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12627:        }
1.269     brouard  12628:       }else{
                   12629:        printf("Internal error moving average\n");
                   12630:        fflush(stdout);
                   12631:        exit(1);
1.219     brouard  12632:       }
                   12633:     }/* end if moving average */
1.227     brouard  12634:     
1.126     brouard  12635:     /*---------- Forecasting ------------------*/
1.296     brouard  12636:     if(prevfcast==1){ 
                   12637:       /*   /\*    if(stepm ==1){*\/ */
                   12638:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12639:       /*This done previously after freqsummary.*/
                   12640:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   12641:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   12642:       
                   12643:       /* } else if (prvforecast==2){ */
                   12644:       /*   /\*    if(stepm ==1){*\/ */
                   12645:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12646:       /* } */
                   12647:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   12648:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  12649:     }
1.269     brouard  12650: 
1.296     brouard  12651:     /* Prevbcasting */
                   12652:     if(prevbcast==1){
1.219     brouard  12653:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12654:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12655:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12656: 
                   12657:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12658: 
                   12659:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12660: 
1.219     brouard  12661:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12662:       fclose(ficresplb);
                   12663: 
1.222     brouard  12664:       hBijx(p, bage, fage, mobaverage);
                   12665:       fclose(ficrespijb);
1.219     brouard  12666: 
1.296     brouard  12667:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   12668:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   12669:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   12670:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   12671:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   12672:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   12673: 
                   12674:       
1.269     brouard  12675:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12676: 
                   12677:       
1.269     brouard  12678:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12679:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12680:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12681:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  12682:     }    /* end  Prevbcasting */
1.268     brouard  12683:  
1.186     brouard  12684:  
                   12685:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12686: 
1.215     brouard  12687:     free_ivector(wav,1,imx);
                   12688:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12689:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12690:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12691:                
                   12692:                
1.127     brouard  12693:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12694:                
1.201     brouard  12695:     strcpy(filerese,"E_");
                   12696:     strcat(filerese,fileresu);
1.126     brouard  12697:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12698:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12699:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12700:     }
1.208     brouard  12701:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12702:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12703: 
                   12704:     pstamp(ficreseij);
1.219     brouard  12705:                
1.235     brouard  12706:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12707:     if (cptcovn < 1){i1=1;}
                   12708:     
                   12709:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12710:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12711:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12712:        continue;
1.219     brouard  12713:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12714:       printf("\n#****** ");
1.225     brouard  12715:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12716:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12717:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12718:       }
                   12719:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12720:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12721:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12722:       }
                   12723:       fprintf(ficreseij,"******\n");
1.235     brouard  12724:       printf("******\n");
1.219     brouard  12725:       
                   12726:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12727:       oldm=oldms;savm=savms;
1.235     brouard  12728:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12729:       
1.219     brouard  12730:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12731:     }
                   12732:     fclose(ficreseij);
1.208     brouard  12733:     printf("done evsij\n");fflush(stdout);
                   12734:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12735: 
1.218     brouard  12736:                
1.227     brouard  12737:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12738:                
1.201     brouard  12739:     strcpy(filerest,"T_");
                   12740:     strcat(filerest,fileresu);
1.127     brouard  12741:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12742:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12743:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12744:     }
1.208     brouard  12745:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12746:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12747:     strcpy(fileresstde,"STDE_");
                   12748:     strcat(fileresstde,fileresu);
1.126     brouard  12749:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12750:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12751:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12752:     }
1.227     brouard  12753:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12754:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12755: 
1.201     brouard  12756:     strcpy(filerescve,"CVE_");
                   12757:     strcat(filerescve,fileresu);
1.126     brouard  12758:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12759:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12760:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12761:     }
1.227     brouard  12762:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12763:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12764: 
1.201     brouard  12765:     strcpy(fileresv,"V_");
                   12766:     strcat(fileresv,fileresu);
1.126     brouard  12767:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12768:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12769:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12770:     }
1.227     brouard  12771:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12772:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12773: 
1.235     brouard  12774:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12775:     if (cptcovn < 1){i1=1;}
                   12776:     
                   12777:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12778:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12779:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12780:        continue;
1.242     brouard  12781:       printf("\n#****** Result for:");
                   12782:       fprintf(ficrest,"\n#****** Result for:");
                   12783:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12784:       for(j=1;j<=cptcoveff;j++){ 
                   12785:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12786:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12787:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12788:       }
1.235     brouard  12789:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12790:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12791:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12792:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12793:       }        
1.208     brouard  12794:       fprintf(ficrest,"******\n");
1.227     brouard  12795:       fprintf(ficlog,"******\n");
                   12796:       printf("******\n");
1.208     brouard  12797:       
                   12798:       fprintf(ficresstdeij,"\n#****** ");
                   12799:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12800:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12801:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12802:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12803:       }
1.235     brouard  12804:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12805:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12806:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12807:       }        
1.208     brouard  12808:       fprintf(ficresstdeij,"******\n");
                   12809:       fprintf(ficrescveij,"******\n");
                   12810:       
                   12811:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12812:       /* pstamp(ficresvij); */
1.225     brouard  12813:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12814:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12815:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12816:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12817:       }        
1.208     brouard  12818:       fprintf(ficresvij,"******\n");
                   12819:       
                   12820:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12821:       oldm=oldms;savm=savms;
1.235     brouard  12822:       printf(" cvevsij ");
                   12823:       fprintf(ficlog, " cvevsij ");
                   12824:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12825:       printf(" end cvevsij \n ");
                   12826:       fprintf(ficlog, " end cvevsij \n ");
                   12827:       
                   12828:       /*
                   12829:        */
                   12830:       /* goto endfree; */
                   12831:       
                   12832:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12833:       pstamp(ficrest);
                   12834:       
1.269     brouard  12835:       epj=vector(1,nlstate+1);
1.208     brouard  12836:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12837:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12838:        cptcod= 0; /* To be deleted */
                   12839:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12840:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12841:        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  12842:        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 ");
                   12843:        if(vpopbased==1)
                   12844:          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);
                   12845:        else
1.288     brouard  12846:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12847:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12848:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12849:        fprintf(ficrest,"\n");
                   12850:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12851:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12852:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12853:        for(age=bage; age <=fage ;age++){
1.235     brouard  12854:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12855:          if (vpopbased==1) {
                   12856:            if(mobilav ==0){
                   12857:              for(i=1; i<=nlstate;i++)
                   12858:                prlim[i][i]=probs[(int)age][i][k];
                   12859:            }else{ /* mobilav */ 
                   12860:              for(i=1; i<=nlstate;i++)
                   12861:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12862:            }
                   12863:          }
1.219     brouard  12864:          
1.227     brouard  12865:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12866:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12867:          /* printf(" age %4.0f ",age); */
                   12868:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12869:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12870:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12871:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12872:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12873:            }
                   12874:            epj[nlstate+1] +=epj[j];
                   12875:          }
                   12876:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12877:          
1.227     brouard  12878:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12879:            for(j=1;j <=nlstate;j++)
                   12880:              vepp += vareij[i][j][(int)age];
                   12881:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12882:          for(j=1;j <=nlstate;j++){
                   12883:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12884:          }
                   12885:          fprintf(ficrest,"\n");
                   12886:        }
1.208     brouard  12887:       } /* End vpopbased */
1.269     brouard  12888:       free_vector(epj,1,nlstate+1);
1.208     brouard  12889:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12890:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12891:       printf("done selection\n");fflush(stdout);
                   12892:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12893:       
1.235     brouard  12894:     } /* End k selection */
1.227     brouard  12895: 
                   12896:     printf("done State-specific expectancies\n");fflush(stdout);
                   12897:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12898: 
1.288     brouard  12899:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12900:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12901: 
1.227     brouard  12902:     
1.290     brouard  12903:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12904:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12905:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12906:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12907:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   12908:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  12909:     free_ivector(tab,1,NCOVMAX);
                   12910:     fclose(ficresstdeij);
                   12911:     fclose(ficrescveij);
                   12912:     fclose(ficresvij);
                   12913:     fclose(ficrest);
                   12914:     fclose(ficpar);
                   12915:     
                   12916:     
1.126     brouard  12917:     /*---------- End : free ----------------*/
1.219     brouard  12918:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  12919:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   12920:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  12921:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   12922:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  12923:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  12924:   /* endfree:*/
                   12925:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12926:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12927:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  12928:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   12929:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   12930:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   12931:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  12932:   free_matrix(matcov,1,npar,1,npar);
                   12933:   free_matrix(hess,1,npar,1,npar);
                   12934:   /*free_vector(delti,1,npar);*/
                   12935:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12936:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  12937:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  12938:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   12939:   
                   12940:   free_ivector(ncodemax,1,NCOVMAX);
                   12941:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   12942:   free_ivector(Dummy,-1,NCOVMAX);
                   12943:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  12944:   free_ivector(DummyV,1,NCOVMAX);
                   12945:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  12946:   free_ivector(Typevar,-1,NCOVMAX);
                   12947:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  12948:   free_ivector(TvarsQ,1,NCOVMAX);
                   12949:   free_ivector(TvarsQind,1,NCOVMAX);
                   12950:   free_ivector(TvarsD,1,NCOVMAX);
                   12951:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  12952:   free_ivector(TvarFD,1,NCOVMAX);
                   12953:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  12954:   free_ivector(TvarF,1,NCOVMAX);
                   12955:   free_ivector(TvarFind,1,NCOVMAX);
                   12956:   free_ivector(TvarV,1,NCOVMAX);
                   12957:   free_ivector(TvarVind,1,NCOVMAX);
                   12958:   free_ivector(TvarA,1,NCOVMAX);
                   12959:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  12960:   free_ivector(TvarFQ,1,NCOVMAX);
                   12961:   free_ivector(TvarFQind,1,NCOVMAX);
                   12962:   free_ivector(TvarVD,1,NCOVMAX);
                   12963:   free_ivector(TvarVDind,1,NCOVMAX);
                   12964:   free_ivector(TvarVQ,1,NCOVMAX);
                   12965:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  12966:   free_ivector(Tvarsel,1,NCOVMAX);
                   12967:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  12968:   free_ivector(Tposprod,1,NCOVMAX);
                   12969:   free_ivector(Tprod,1,NCOVMAX);
                   12970:   free_ivector(Tvaraff,1,NCOVMAX);
                   12971:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   12972:   free_ivector(Tage,1,NCOVMAX);
                   12973:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  12974:   free_ivector(TmodelInvind,1,NCOVMAX);
                   12975:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  12976:   
                   12977:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   12978:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  12979:   fflush(fichtm);
                   12980:   fflush(ficgp);
                   12981:   
1.227     brouard  12982:   
1.126     brouard  12983:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  12984:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   12985:     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  12986:   }else{
                   12987:     printf("End of Imach\n");
                   12988:     fprintf(ficlog,"End of Imach\n");
                   12989:   }
                   12990:   printf("See log file on %s\n",filelog);
                   12991:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  12992:   /*(void) gettimeofday(&end_time,&tzp);*/
                   12993:   rend_time = time(NULL);  
                   12994:   end_time = *localtime(&rend_time);
                   12995:   /* tml = *localtime(&end_time.tm_sec); */
                   12996:   strcpy(strtend,asctime(&end_time));
1.126     brouard  12997:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   12998:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  12999:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13000:   
1.157     brouard  13001:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13002:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13003:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13004:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13005: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13006:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13007:   fclose(fichtm);
                   13008:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13009:   fclose(fichtmcov);
                   13010:   fclose(ficgp);
                   13011:   fclose(ficlog);
                   13012:   /*------ End -----------*/
1.227     brouard  13013:   
1.281     brouard  13014: 
                   13015: /* Executes gnuplot */
1.227     brouard  13016:   
                   13017:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13018: #ifdef WIN32
1.227     brouard  13019:   if (_chdir(pathcd) != 0)
                   13020:     printf("Can't move to directory %s!\n",path);
                   13021:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13022: #else
1.227     brouard  13023:     if(chdir(pathcd) != 0)
                   13024:       printf("Can't move to directory %s!\n", path);
                   13025:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13026: #endif 
1.126     brouard  13027:     printf("Current directory %s!\n",pathcd);
                   13028:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13029:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13030: #ifdef _WIN32
1.126     brouard  13031:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13032: #endif
                   13033:   if(!stat(plotcmd,&info)){
1.158     brouard  13034:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13035:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13036:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13037:     }else
                   13038:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13039: #ifdef __unix
1.126     brouard  13040:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13041:     if(!stat(plotcmd,&info)){
1.158     brouard  13042:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13043:     }else
                   13044:       strcpy(pplotcmd,plotcmd);
                   13045: #endif
                   13046:   }else
                   13047:     strcpy(pplotcmd,plotcmd);
                   13048:   
                   13049:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13050:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13051:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13052:   
1.126     brouard  13053:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13054:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13055:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13056:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13057:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13058:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13059:       strcpy(plotcmd,pplotcmd);
                   13060:     }
1.126     brouard  13061:   }
1.158     brouard  13062:   printf(" Successful, please wait...");
1.126     brouard  13063:   while (z[0] != 'q') {
                   13064:     /* chdir(path); */
1.154     brouard  13065:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13066:     scanf("%s",z);
                   13067: /*     if (z[0] == 'c') system("./imach"); */
                   13068:     if (z[0] == 'e') {
1.158     brouard  13069: #ifdef __APPLE__
1.152     brouard  13070:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13071: #elif __linux
                   13072:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13073: #else
1.152     brouard  13074:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13075: #endif
                   13076:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13077:       system(pplotcmd);
1.126     brouard  13078:     }
                   13079:     else if (z[0] == 'g') system(plotcmd);
                   13080:     else if (z[0] == 'q') exit(0);
                   13081:   }
1.227     brouard  13082: end:
1.126     brouard  13083:   while (z[0] != 'q') {
1.195     brouard  13084:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13085:     scanf("%s",z);
                   13086:   }
1.283     brouard  13087:   printf("End\n");
1.282     brouard  13088:   exit(0);
1.126     brouard  13089: }

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