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

1.242   ! brouard     1: /* $Id: imach.c,v 1.241 2016/08/29 17:17:25 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.242   ! brouard     4:   Revision 1.241  2016/08/29 17:17:25  brouard
        !             5:   Summary: gnuplot problem in Back projection to fix
        !             6: 
1.241     brouard     7:   Revision 1.240  2016/08/29 07:53:18  brouard
                      8:   Summary: Better
                      9: 
1.240     brouard    10:   Revision 1.239  2016/08/26 15:51:03  brouard
                     11:   Summary: Improvement in Powell output in order to copy and paste
                     12: 
                     13:   Author:
                     14: 
1.239     brouard    15:   Revision 1.238  2016/08/26 14:23:35  brouard
                     16:   Summary: Starting tests of 0.99
                     17: 
1.238     brouard    18:   Revision 1.237  2016/08/26 09:20:19  brouard
                     19:   Summary: to valgrind
                     20: 
1.237     brouard    21:   Revision 1.236  2016/08/25 10:50:18  brouard
                     22:   *** empty log message ***
                     23: 
1.236     brouard    24:   Revision 1.235  2016/08/25 06:59:23  brouard
                     25:   *** empty log message ***
                     26: 
1.235     brouard    27:   Revision 1.234  2016/08/23 16:51:20  brouard
                     28:   *** empty log message ***
                     29: 
1.234     brouard    30:   Revision 1.233  2016/08/23 07:40:50  brouard
                     31:   Summary: not working
                     32: 
1.233     brouard    33:   Revision 1.232  2016/08/22 14:20:21  brouard
                     34:   Summary: not working
                     35: 
1.232     brouard    36:   Revision 1.231  2016/08/22 07:17:15  brouard
                     37:   Summary: not working
                     38: 
1.231     brouard    39:   Revision 1.230  2016/08/22 06:55:53  brouard
                     40:   Summary: Not working
                     41: 
1.230     brouard    42:   Revision 1.229  2016/07/23 09:45:53  brouard
                     43:   Summary: Completing for func too
                     44: 
1.229     brouard    45:   Revision 1.228  2016/07/22 17:45:30  brouard
                     46:   Summary: Fixing some arrays, still debugging
                     47: 
1.227     brouard    48:   Revision 1.226  2016/07/12 18:42:34  brouard
                     49:   Summary: temp
                     50: 
1.226     brouard    51:   Revision 1.225  2016/07/12 08:40:03  brouard
                     52:   Summary: saving but not running
                     53: 
1.225     brouard    54:   Revision 1.224  2016/07/01 13:16:01  brouard
                     55:   Summary: Fixes
                     56: 
1.224     brouard    57:   Revision 1.223  2016/02/19 09:23:35  brouard
                     58:   Summary: temporary
                     59: 
1.223     brouard    60:   Revision 1.222  2016/02/17 08:14:50  brouard
                     61:   Summary: Probably last 0.98 stable version 0.98r6
                     62: 
1.222     brouard    63:   Revision 1.221  2016/02/15 23:35:36  brouard
                     64:   Summary: minor bug
                     65: 
1.220     brouard    66:   Revision 1.219  2016/02/15 00:48:12  brouard
                     67:   *** empty log message ***
                     68: 
1.219     brouard    69:   Revision 1.218  2016/02/12 11:29:23  brouard
                     70:   Summary: 0.99 Back projections
                     71: 
1.218     brouard    72:   Revision 1.217  2015/12/23 17:18:31  brouard
                     73:   Summary: Experimental backcast
                     74: 
1.217     brouard    75:   Revision 1.216  2015/12/18 17:32:11  brouard
                     76:   Summary: 0.98r4 Warning and status=-2
                     77: 
                     78:   Version 0.98r4 is now:
                     79:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     80:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     81:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     82: 
1.216     brouard    83:   Revision 1.215  2015/12/16 08:52:24  brouard
                     84:   Summary: 0.98r4 working
                     85: 
1.215     brouard    86:   Revision 1.214  2015/12/16 06:57:54  brouard
                     87:   Summary: temporary not working
                     88: 
1.214     brouard    89:   Revision 1.213  2015/12/11 18:22:17  brouard
                     90:   Summary: 0.98r4
                     91: 
1.213     brouard    92:   Revision 1.212  2015/11/21 12:47:24  brouard
                     93:   Summary: minor typo
                     94: 
1.212     brouard    95:   Revision 1.211  2015/11/21 12:41:11  brouard
                     96:   Summary: 0.98r3 with some graph of projected cross-sectional
                     97: 
                     98:   Author: Nicolas Brouard
                     99: 
1.211     brouard   100:   Revision 1.210  2015/11/18 17:41:20  brouard
                    101:   Summary: Start working on projected prevalences
                    102: 
1.210     brouard   103:   Revision 1.209  2015/11/17 22:12:03  brouard
                    104:   Summary: Adding ftolpl parameter
                    105:   Author: N Brouard
                    106: 
                    107:   We had difficulties to get smoothed confidence intervals. It was due
                    108:   to the period prevalence which wasn't computed accurately. The inner
                    109:   parameter ftolpl is now an outer parameter of the .imach parameter
                    110:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    111:   computation are long.
                    112: 
1.209     brouard   113:   Revision 1.208  2015/11/17 14:31:57  brouard
                    114:   Summary: temporary
                    115: 
1.208     brouard   116:   Revision 1.207  2015/10/27 17:36:57  brouard
                    117:   *** empty log message ***
                    118: 
1.207     brouard   119:   Revision 1.206  2015/10/24 07:14:11  brouard
                    120:   *** empty log message ***
                    121: 
1.206     brouard   122:   Revision 1.205  2015/10/23 15:50:53  brouard
                    123:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    124: 
1.205     brouard   125:   Revision 1.204  2015/10/01 16:20:26  brouard
                    126:   Summary: Some new graphs of contribution to likelihood
                    127: 
1.204     brouard   128:   Revision 1.203  2015/09/30 17:45:14  brouard
                    129:   Summary: looking at better estimation of the hessian
                    130: 
                    131:   Also a better criteria for convergence to the period prevalence And
                    132:   therefore adding the number of years needed to converge. (The
                    133:   prevalence in any alive state shold sum to one
                    134: 
1.203     brouard   135:   Revision 1.202  2015/09/22 19:45:16  brouard
                    136:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    137: 
1.202     brouard   138:   Revision 1.201  2015/09/15 17:34:58  brouard
                    139:   Summary: 0.98r0
                    140: 
                    141:   - Some new graphs like suvival functions
                    142:   - Some bugs fixed like model=1+age+V2.
                    143: 
1.201     brouard   144:   Revision 1.200  2015/09/09 16:53:55  brouard
                    145:   Summary: Big bug thanks to Flavia
                    146: 
                    147:   Even model=1+age+V2. did not work anymore
                    148: 
1.200     brouard   149:   Revision 1.199  2015/09/07 14:09:23  brouard
                    150:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    151: 
1.199     brouard   152:   Revision 1.198  2015/09/03 07:14:39  brouard
                    153:   Summary: 0.98q5 Flavia
                    154: 
1.198     brouard   155:   Revision 1.197  2015/09/01 18:24:39  brouard
                    156:   *** empty log message ***
                    157: 
1.197     brouard   158:   Revision 1.196  2015/08/18 23:17:52  brouard
                    159:   Summary: 0.98q5
                    160: 
1.196     brouard   161:   Revision 1.195  2015/08/18 16:28:39  brouard
                    162:   Summary: Adding a hack for testing purpose
                    163: 
                    164:   After reading the title, ftol and model lines, if the comment line has
                    165:   a q, starting with #q, the answer at the end of the run is quit. It
                    166:   permits to run test files in batch with ctest. The former workaround was
                    167:   $ echo q | imach foo.imach
                    168: 
1.195     brouard   169:   Revision 1.194  2015/08/18 13:32:00  brouard
                    170:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    171: 
1.194     brouard   172:   Revision 1.193  2015/08/04 07:17:42  brouard
                    173:   Summary: 0.98q4
                    174: 
1.193     brouard   175:   Revision 1.192  2015/07/16 16:49:02  brouard
                    176:   Summary: Fixing some outputs
                    177: 
1.192     brouard   178:   Revision 1.191  2015/07/14 10:00:33  brouard
                    179:   Summary: Some fixes
                    180: 
1.191     brouard   181:   Revision 1.190  2015/05/05 08:51:13  brouard
                    182:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    183: 
                    184:   Fix 1+age+.
                    185: 
1.190     brouard   186:   Revision 1.189  2015/04/30 14:45:16  brouard
                    187:   Summary: 0.98q2
                    188: 
1.189     brouard   189:   Revision 1.188  2015/04/30 08:27:53  brouard
                    190:   *** empty log message ***
                    191: 
1.188     brouard   192:   Revision 1.187  2015/04/29 09:11:15  brouard
                    193:   *** empty log message ***
                    194: 
1.187     brouard   195:   Revision 1.186  2015/04/23 12:01:52  brouard
                    196:   Summary: V1*age is working now, version 0.98q1
                    197: 
                    198:   Some codes had been disabled in order to simplify and Vn*age was
                    199:   working in the optimization phase, ie, giving correct MLE parameters,
                    200:   but, as usual, outputs were not correct and program core dumped.
                    201: 
1.186     brouard   202:   Revision 1.185  2015/03/11 13:26:42  brouard
                    203:   Summary: Inclusion of compile and links command line for Intel Compiler
                    204: 
1.185     brouard   205:   Revision 1.184  2015/03/11 11:52:39  brouard
                    206:   Summary: Back from Windows 8. Intel Compiler
                    207: 
1.184     brouard   208:   Revision 1.183  2015/03/10 20:34:32  brouard
                    209:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    210: 
                    211:   We use directest instead of original Powell test; probably no
                    212:   incidence on the results, but better justifications;
                    213:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    214:   wrong results.
                    215: 
1.183     brouard   216:   Revision 1.182  2015/02/12 08:19:57  brouard
                    217:   Summary: Trying to keep directest which seems simpler and more general
                    218:   Author: Nicolas Brouard
                    219: 
1.182     brouard   220:   Revision 1.181  2015/02/11 23:22:24  brouard
                    221:   Summary: Comments on Powell added
                    222: 
                    223:   Author:
                    224: 
1.181     brouard   225:   Revision 1.180  2015/02/11 17:33:45  brouard
                    226:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    227: 
1.180     brouard   228:   Revision 1.179  2015/01/04 09:57:06  brouard
                    229:   Summary: back to OS/X
                    230: 
1.179     brouard   231:   Revision 1.178  2015/01/04 09:35:48  brouard
                    232:   *** empty log message ***
                    233: 
1.178     brouard   234:   Revision 1.177  2015/01/03 18:40:56  brouard
                    235:   Summary: Still testing ilc32 on OSX
                    236: 
1.177     brouard   237:   Revision 1.176  2015/01/03 16:45:04  brouard
                    238:   *** empty log message ***
                    239: 
1.176     brouard   240:   Revision 1.175  2015/01/03 16:33:42  brouard
                    241:   *** empty log message ***
                    242: 
1.175     brouard   243:   Revision 1.174  2015/01/03 16:15:49  brouard
                    244:   Summary: Still in cross-compilation
                    245: 
1.174     brouard   246:   Revision 1.173  2015/01/03 12:06:26  brouard
                    247:   Summary: trying to detect cross-compilation
                    248: 
1.173     brouard   249:   Revision 1.172  2014/12/27 12:07:47  brouard
                    250:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    251: 
1.172     brouard   252:   Revision 1.171  2014/12/23 13:26:59  brouard
                    253:   Summary: Back from Visual C
                    254: 
                    255:   Still problem with utsname.h on Windows
                    256: 
1.171     brouard   257:   Revision 1.170  2014/12/23 11:17:12  brouard
                    258:   Summary: Cleaning some \%% back to %%
                    259: 
                    260:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    261: 
1.170     brouard   262:   Revision 1.169  2014/12/22 23:08:31  brouard
                    263:   Summary: 0.98p
                    264: 
                    265:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    266: 
1.169     brouard   267:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   268:   Summary: update
1.169     brouard   269: 
1.168     brouard   270:   Revision 1.167  2014/12/22 13:50:56  brouard
                    271:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    272: 
                    273:   Testing on Linux 64
                    274: 
1.167     brouard   275:   Revision 1.166  2014/12/22 11:40:47  brouard
                    276:   *** empty log message ***
                    277: 
1.166     brouard   278:   Revision 1.165  2014/12/16 11:20:36  brouard
                    279:   Summary: After compiling on Visual C
                    280: 
                    281:   * imach.c (Module): Merging 1.61 to 1.162
                    282: 
1.165     brouard   283:   Revision 1.164  2014/12/16 10:52:11  brouard
                    284:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    285: 
                    286:   * imach.c (Module): Merging 1.61 to 1.162
                    287: 
1.164     brouard   288:   Revision 1.163  2014/12/16 10:30:11  brouard
                    289:   * imach.c (Module): Merging 1.61 to 1.162
                    290: 
1.163     brouard   291:   Revision 1.162  2014/09/25 11:43:39  brouard
                    292:   Summary: temporary backup 0.99!
                    293: 
1.162     brouard   294:   Revision 1.1  2014/09/16 11:06:58  brouard
                    295:   Summary: With some code (wrong) for nlopt
                    296: 
                    297:   Author:
                    298: 
                    299:   Revision 1.161  2014/09/15 20:41:41  brouard
                    300:   Summary: Problem with macro SQR on Intel compiler
                    301: 
1.161     brouard   302:   Revision 1.160  2014/09/02 09:24:05  brouard
                    303:   *** empty log message ***
                    304: 
1.160     brouard   305:   Revision 1.159  2014/09/01 10:34:10  brouard
                    306:   Summary: WIN32
                    307:   Author: Brouard
                    308: 
1.159     brouard   309:   Revision 1.158  2014/08/27 17:11:51  brouard
                    310:   *** empty log message ***
                    311: 
1.158     brouard   312:   Revision 1.157  2014/08/27 16:26:55  brouard
                    313:   Summary: Preparing windows Visual studio version
                    314:   Author: Brouard
                    315: 
                    316:   In order to compile on Visual studio, time.h is now correct and time_t
                    317:   and tm struct should be used. difftime should be used but sometimes I
                    318:   just make the differences in raw time format (time(&now).
                    319:   Trying to suppress #ifdef LINUX
                    320:   Add xdg-open for __linux in order to open default browser.
                    321: 
1.157     brouard   322:   Revision 1.156  2014/08/25 20:10:10  brouard
                    323:   *** empty log message ***
                    324: 
1.156     brouard   325:   Revision 1.155  2014/08/25 18:32:34  brouard
                    326:   Summary: New compile, minor changes
                    327:   Author: Brouard
                    328: 
1.155     brouard   329:   Revision 1.154  2014/06/20 17:32:08  brouard
                    330:   Summary: Outputs now all graphs of convergence to period prevalence
                    331: 
1.154     brouard   332:   Revision 1.153  2014/06/20 16:45:46  brouard
                    333:   Summary: If 3 live state, convergence to period prevalence on same graph
                    334:   Author: Brouard
                    335: 
1.153     brouard   336:   Revision 1.152  2014/06/18 17:54:09  brouard
                    337:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    338: 
1.152     brouard   339:   Revision 1.151  2014/06/18 16:43:30  brouard
                    340:   *** empty log message ***
                    341: 
1.151     brouard   342:   Revision 1.150  2014/06/18 16:42:35  brouard
                    343:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    344:   Author: brouard
                    345: 
1.150     brouard   346:   Revision 1.149  2014/06/18 15:51:14  brouard
                    347:   Summary: Some fixes in parameter files errors
                    348:   Author: Nicolas Brouard
                    349: 
1.149     brouard   350:   Revision 1.148  2014/06/17 17:38:48  brouard
                    351:   Summary: Nothing new
                    352:   Author: Brouard
                    353: 
                    354:   Just a new packaging for OS/X version 0.98nS
                    355: 
1.148     brouard   356:   Revision 1.147  2014/06/16 10:33:11  brouard
                    357:   *** empty log message ***
                    358: 
1.147     brouard   359:   Revision 1.146  2014/06/16 10:20:28  brouard
                    360:   Summary: Merge
                    361:   Author: Brouard
                    362: 
                    363:   Merge, before building revised version.
                    364: 
1.146     brouard   365:   Revision 1.145  2014/06/10 21:23:15  brouard
                    366:   Summary: Debugging with valgrind
                    367:   Author: Nicolas Brouard
                    368: 
                    369:   Lot of changes in order to output the results with some covariates
                    370:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    371:   improve the code.
                    372:   No more memory valgrind error but a lot has to be done in order to
                    373:   continue the work of splitting the code into subroutines.
                    374:   Also, decodemodel has been improved. Tricode is still not
                    375:   optimal. nbcode should be improved. Documentation has been added in
                    376:   the source code.
                    377: 
1.144     brouard   378:   Revision 1.143  2014/01/26 09:45:38  brouard
                    379:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    380: 
                    381:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    382:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    383: 
1.143     brouard   384:   Revision 1.142  2014/01/26 03:57:36  brouard
                    385:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    386: 
                    387:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    388: 
1.142     brouard   389:   Revision 1.141  2014/01/26 02:42:01  brouard
                    390:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    391: 
1.141     brouard   392:   Revision 1.140  2011/09/02 10:37:54  brouard
                    393:   Summary: times.h is ok with mingw32 now.
                    394: 
1.140     brouard   395:   Revision 1.139  2010/06/14 07:50:17  brouard
                    396:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    397:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    398: 
1.139     brouard   399:   Revision 1.138  2010/04/30 18:19:40  brouard
                    400:   *** empty log message ***
                    401: 
1.138     brouard   402:   Revision 1.137  2010/04/29 18:11:38  brouard
                    403:   (Module): Checking covariates for more complex models
                    404:   than V1+V2. A lot of change to be done. Unstable.
                    405: 
1.137     brouard   406:   Revision 1.136  2010/04/26 20:30:53  brouard
                    407:   (Module): merging some libgsl code. Fixing computation
                    408:   of likelione (using inter/intrapolation if mle = 0) in order to
                    409:   get same likelihood as if mle=1.
                    410:   Some cleaning of code and comments added.
                    411: 
1.136     brouard   412:   Revision 1.135  2009/10/29 15:33:14  brouard
                    413:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    414: 
1.135     brouard   415:   Revision 1.134  2009/10/29 13:18:53  brouard
                    416:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    417: 
1.134     brouard   418:   Revision 1.133  2009/07/06 10:21:25  brouard
                    419:   just nforces
                    420: 
1.133     brouard   421:   Revision 1.132  2009/07/06 08:22:05  brouard
                    422:   Many tings
                    423: 
1.132     brouard   424:   Revision 1.131  2009/06/20 16:22:47  brouard
                    425:   Some dimensions resccaled
                    426: 
1.131     brouard   427:   Revision 1.130  2009/05/26 06:44:34  brouard
                    428:   (Module): Max Covariate is now set to 20 instead of 8. A
                    429:   lot of cleaning with variables initialized to 0. Trying to make
                    430:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    431: 
1.130     brouard   432:   Revision 1.129  2007/08/31 13:49:27  lievre
                    433:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    434: 
1.129     lievre    435:   Revision 1.128  2006/06/30 13:02:05  brouard
                    436:   (Module): Clarifications on computing e.j
                    437: 
1.128     brouard   438:   Revision 1.127  2006/04/28 18:11:50  brouard
                    439:   (Module): Yes the sum of survivors was wrong since
                    440:   imach-114 because nhstepm was no more computed in the age
                    441:   loop. Now we define nhstepma in the age loop.
                    442:   (Module): In order to speed up (in case of numerous covariates) we
                    443:   compute health expectancies (without variances) in a first step
                    444:   and then all the health expectancies with variances or standard
                    445:   deviation (needs data from the Hessian matrices) which slows the
                    446:   computation.
                    447:   In the future we should be able to stop the program is only health
                    448:   expectancies and graph are needed without standard deviations.
                    449: 
1.127     brouard   450:   Revision 1.126  2006/04/28 17:23:28  brouard
                    451:   (Module): Yes the sum of survivors was wrong since
                    452:   imach-114 because nhstepm was no more computed in the age
                    453:   loop. Now we define nhstepma in the age loop.
                    454:   Version 0.98h
                    455: 
1.126     brouard   456:   Revision 1.125  2006/04/04 15:20:31  lievre
                    457:   Errors in calculation of health expectancies. Age was not initialized.
                    458:   Forecasting file added.
                    459: 
                    460:   Revision 1.124  2006/03/22 17:13:53  lievre
                    461:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    462:   The log-likelihood is printed in the log file
                    463: 
                    464:   Revision 1.123  2006/03/20 10:52:43  brouard
                    465:   * imach.c (Module): <title> changed, corresponds to .htm file
                    466:   name. <head> headers where missing.
                    467: 
                    468:   * imach.c (Module): Weights can have a decimal point as for
                    469:   English (a comma might work with a correct LC_NUMERIC environment,
                    470:   otherwise the weight is truncated).
                    471:   Modification of warning when the covariates values are not 0 or
                    472:   1.
                    473:   Version 0.98g
                    474: 
                    475:   Revision 1.122  2006/03/20 09:45:41  brouard
                    476:   (Module): Weights can have a decimal point as for
                    477:   English (a comma might work with a correct LC_NUMERIC environment,
                    478:   otherwise the weight is truncated).
                    479:   Modification of warning when the covariates values are not 0 or
                    480:   1.
                    481:   Version 0.98g
                    482: 
                    483:   Revision 1.121  2006/03/16 17:45:01  lievre
                    484:   * imach.c (Module): Comments concerning covariates added
                    485: 
                    486:   * imach.c (Module): refinements in the computation of lli if
                    487:   status=-2 in order to have more reliable computation if stepm is
                    488:   not 1 month. Version 0.98f
                    489: 
                    490:   Revision 1.120  2006/03/16 15:10:38  lievre
                    491:   (Module): refinements in the computation of lli if
                    492:   status=-2 in order to have more reliable computation if stepm is
                    493:   not 1 month. Version 0.98f
                    494: 
                    495:   Revision 1.119  2006/03/15 17:42:26  brouard
                    496:   (Module): Bug if status = -2, the loglikelihood was
                    497:   computed as likelihood omitting the logarithm. Version O.98e
                    498: 
                    499:   Revision 1.118  2006/03/14 18:20:07  brouard
                    500:   (Module): varevsij Comments added explaining the second
                    501:   table of variances if popbased=1 .
                    502:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    503:   (Module): Function pstamp added
                    504:   (Module): Version 0.98d
                    505: 
                    506:   Revision 1.117  2006/03/14 17:16:22  brouard
                    507:   (Module): varevsij Comments added explaining the second
                    508:   table of variances if popbased=1 .
                    509:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    510:   (Module): Function pstamp added
                    511:   (Module): Version 0.98d
                    512: 
                    513:   Revision 1.116  2006/03/06 10:29:27  brouard
                    514:   (Module): Variance-covariance wrong links and
                    515:   varian-covariance of ej. is needed (Saito).
                    516: 
                    517:   Revision 1.115  2006/02/27 12:17:45  brouard
                    518:   (Module): One freematrix added in mlikeli! 0.98c
                    519: 
                    520:   Revision 1.114  2006/02/26 12:57:58  brouard
                    521:   (Module): Some improvements in processing parameter
                    522:   filename with strsep.
                    523: 
                    524:   Revision 1.113  2006/02/24 14:20:24  brouard
                    525:   (Module): Memory leaks checks with valgrind and:
                    526:   datafile was not closed, some imatrix were not freed and on matrix
                    527:   allocation too.
                    528: 
                    529:   Revision 1.112  2006/01/30 09:55:26  brouard
                    530:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    531: 
                    532:   Revision 1.111  2006/01/25 20:38:18  brouard
                    533:   (Module): Lots of cleaning and bugs added (Gompertz)
                    534:   (Module): Comments can be added in data file. Missing date values
                    535:   can be a simple dot '.'.
                    536: 
                    537:   Revision 1.110  2006/01/25 00:51:50  brouard
                    538:   (Module): Lots of cleaning and bugs added (Gompertz)
                    539: 
                    540:   Revision 1.109  2006/01/24 19:37:15  brouard
                    541:   (Module): Comments (lines starting with a #) are allowed in data.
                    542: 
                    543:   Revision 1.108  2006/01/19 18:05:42  lievre
                    544:   Gnuplot problem appeared...
                    545:   To be fixed
                    546: 
                    547:   Revision 1.107  2006/01/19 16:20:37  brouard
                    548:   Test existence of gnuplot in imach path
                    549: 
                    550:   Revision 1.106  2006/01/19 13:24:36  brouard
                    551:   Some cleaning and links added in html output
                    552: 
                    553:   Revision 1.105  2006/01/05 20:23:19  lievre
                    554:   *** empty log message ***
                    555: 
                    556:   Revision 1.104  2005/09/30 16:11:43  lievre
                    557:   (Module): sump fixed, loop imx fixed, and simplifications.
                    558:   (Module): If the status is missing at the last wave but we know
                    559:   that the person is alive, then we can code his/her status as -2
                    560:   (instead of missing=-1 in earlier versions) and his/her
                    561:   contributions to the likelihood is 1 - Prob of dying from last
                    562:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    563:   the healthy state at last known wave). Version is 0.98
                    564: 
                    565:   Revision 1.103  2005/09/30 15:54:49  lievre
                    566:   (Module): sump fixed, loop imx fixed, and simplifications.
                    567: 
                    568:   Revision 1.102  2004/09/15 17:31:30  brouard
                    569:   Add the possibility to read data file including tab characters.
                    570: 
                    571:   Revision 1.101  2004/09/15 10:38:38  brouard
                    572:   Fix on curr_time
                    573: 
                    574:   Revision 1.100  2004/07/12 18:29:06  brouard
                    575:   Add version for Mac OS X. Just define UNIX in Makefile
                    576: 
                    577:   Revision 1.99  2004/06/05 08:57:40  brouard
                    578:   *** empty log message ***
                    579: 
                    580:   Revision 1.98  2004/05/16 15:05:56  brouard
                    581:   New version 0.97 . First attempt to estimate force of mortality
                    582:   directly from the data i.e. without the need of knowing the health
                    583:   state at each age, but using a Gompertz model: log u =a + b*age .
                    584:   This is the basic analysis of mortality and should be done before any
                    585:   other analysis, in order to test if the mortality estimated from the
                    586:   cross-longitudinal survey is different from the mortality estimated
                    587:   from other sources like vital statistic data.
                    588: 
                    589:   The same imach parameter file can be used but the option for mle should be -3.
                    590: 
1.133     brouard   591:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   592:   former routines in order to include the new code within the former code.
                    593: 
                    594:   The output is very simple: only an estimate of the intercept and of
                    595:   the slope with 95% confident intervals.
                    596: 
                    597:   Current limitations:
                    598:   A) Even if you enter covariates, i.e. with the
                    599:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    600:   B) There is no computation of Life Expectancy nor Life Table.
                    601: 
                    602:   Revision 1.97  2004/02/20 13:25:42  lievre
                    603:   Version 0.96d. Population forecasting command line is (temporarily)
                    604:   suppressed.
                    605: 
                    606:   Revision 1.96  2003/07/15 15:38:55  brouard
                    607:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    608:   rewritten within the same printf. Workaround: many printfs.
                    609: 
                    610:   Revision 1.95  2003/07/08 07:54:34  brouard
                    611:   * imach.c (Repository):
                    612:   (Repository): Using imachwizard code to output a more meaningful covariance
                    613:   matrix (cov(a12,c31) instead of numbers.
                    614: 
                    615:   Revision 1.94  2003/06/27 13:00:02  brouard
                    616:   Just cleaning
                    617: 
                    618:   Revision 1.93  2003/06/25 16:33:55  brouard
                    619:   (Module): On windows (cygwin) function asctime_r doesn't
                    620:   exist so I changed back to asctime which exists.
                    621:   (Module): Version 0.96b
                    622: 
                    623:   Revision 1.92  2003/06/25 16:30:45  brouard
                    624:   (Module): On windows (cygwin) function asctime_r doesn't
                    625:   exist so I changed back to asctime which exists.
                    626: 
                    627:   Revision 1.91  2003/06/25 15:30:29  brouard
                    628:   * imach.c (Repository): Duplicated warning errors corrected.
                    629:   (Repository): Elapsed time after each iteration is now output. It
                    630:   helps to forecast when convergence will be reached. Elapsed time
                    631:   is stamped in powell.  We created a new html file for the graphs
                    632:   concerning matrix of covariance. It has extension -cov.htm.
                    633: 
                    634:   Revision 1.90  2003/06/24 12:34:15  brouard
                    635:   (Module): Some bugs corrected for windows. Also, when
                    636:   mle=-1 a template is output in file "or"mypar.txt with the design
                    637:   of the covariance matrix to be input.
                    638: 
                    639:   Revision 1.89  2003/06/24 12:30:52  brouard
                    640:   (Module): Some bugs corrected for windows. Also, when
                    641:   mle=-1 a template is output in file "or"mypar.txt with the design
                    642:   of the covariance matrix to be input.
                    643: 
                    644:   Revision 1.88  2003/06/23 17:54:56  brouard
                    645:   * 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.
                    646: 
                    647:   Revision 1.87  2003/06/18 12:26:01  brouard
                    648:   Version 0.96
                    649: 
                    650:   Revision 1.86  2003/06/17 20:04:08  brouard
                    651:   (Module): Change position of html and gnuplot routines and added
                    652:   routine fileappend.
                    653: 
                    654:   Revision 1.85  2003/06/17 13:12:43  brouard
                    655:   * imach.c (Repository): Check when date of death was earlier that
                    656:   current date of interview. It may happen when the death was just
                    657:   prior to the death. In this case, dh was negative and likelihood
                    658:   was wrong (infinity). We still send an "Error" but patch by
                    659:   assuming that the date of death was just one stepm after the
                    660:   interview.
                    661:   (Repository): Because some people have very long ID (first column)
                    662:   we changed int to long in num[] and we added a new lvector for
                    663:   memory allocation. But we also truncated to 8 characters (left
                    664:   truncation)
                    665:   (Repository): No more line truncation errors.
                    666: 
                    667:   Revision 1.84  2003/06/13 21:44:43  brouard
                    668:   * imach.c (Repository): Replace "freqsummary" at a correct
                    669:   place. It differs from routine "prevalence" which may be called
                    670:   many times. Probs is memory consuming and must be used with
                    671:   parcimony.
                    672:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    673: 
                    674:   Revision 1.83  2003/06/10 13:39:11  lievre
                    675:   *** empty log message ***
                    676: 
                    677:   Revision 1.82  2003/06/05 15:57:20  brouard
                    678:   Add log in  imach.c and  fullversion number is now printed.
                    679: 
                    680: */
                    681: /*
                    682:    Interpolated Markov Chain
                    683: 
                    684:   Short summary of the programme:
                    685:   
1.227     brouard   686:   This program computes Healthy Life Expectancies or State-specific
                    687:   (if states aren't health statuses) Expectancies from
                    688:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    689: 
                    690:   -1- a first survey ("cross") where individuals from different ages
                    691:   are interviewed on their health status or degree of disability (in
                    692:   the case of a health survey which is our main interest)
                    693: 
                    694:   -2- at least a second wave of interviews ("longitudinal") which
                    695:   measure each change (if any) in individual health status.  Health
                    696:   expectancies are computed from the time spent in each health state
                    697:   according to a model. More health states you consider, more time is
                    698:   necessary to reach the Maximum Likelihood of the parameters involved
                    699:   in the model.  The simplest model is the multinomial logistic model
                    700:   where pij is the probability to be observed in state j at the second
                    701:   wave conditional to be observed in state i at the first
                    702:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    703:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    704:   have a more complex model than "constant and age", you should modify
                    705:   the program where the markup *Covariates have to be included here
                    706:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   707:   convergence.
                    708: 
                    709:   The advantage of this computer programme, compared to a simple
                    710:   multinomial logistic model, is clear when the delay between waves is not
                    711:   identical for each individual. Also, if a individual missed an
                    712:   intermediate interview, the information is lost, but taken into
                    713:   account using an interpolation or extrapolation.  
                    714: 
                    715:   hPijx is the probability to be observed in state i at age x+h
                    716:   conditional to the observed state i at age x. The delay 'h' can be
                    717:   split into an exact number (nh*stepm) of unobserved intermediate
                    718:   states. This elementary transition (by month, quarter,
                    719:   semester or year) is modelled as a multinomial logistic.  The hPx
                    720:   matrix is simply the matrix product of nh*stepm elementary matrices
                    721:   and the contribution of each individual to the likelihood is simply
                    722:   hPijx.
                    723: 
                    724:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   725:   of the life expectancies. It also computes the period (stable) prevalence.
                    726: 
                    727: Back prevalence and projections:
1.227     brouard   728: 
                    729:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    730:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    731:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    732:    mobilavproj)
                    733: 
                    734:     Computes the back prevalence limit for any combination of
                    735:     covariate values k at any age between ageminpar and agemaxpar and
                    736:     returns it in **bprlim. In the loops,
                    737: 
                    738:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    739:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    740: 
                    741:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   742:    Computes for any combination of covariates k and any age between bage and fage 
                    743:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    744:                        oldm=oldms;savm=savms;
1.227     brouard   745: 
                    746:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   747:      Computes the transition matrix starting at age 'age' over
                    748:      'nhstepm*hstepm*stepm' months (i.e. until
                    749:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   750:      nhstepm*hstepm matrices. 
                    751: 
                    752:      Returns p3mat[i][j][h] after calling
                    753:      p3mat[i][j][h]=matprod2(newm,
                    754:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    755:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    756:      oldm);
1.226     brouard   757: 
                    758: Important routines
                    759: 
                    760: - func (or funcone), computes logit (pij) distinguishing
                    761:   o fixed variables (single or product dummies or quantitative);
                    762:   o varying variables by:
                    763:    (1) wave (single, product dummies, quantitative), 
                    764:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    765:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    766:        % varying dummy (not done) or quantitative (not done);
                    767: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    768:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    769: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    770:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    771:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   772: 
1.226     brouard   773: 
                    774:   
1.133     brouard   775:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    776:            Institut national d'études démographiques, Paris.
1.126     brouard   777:   This software have been partly granted by Euro-REVES, a concerted action
                    778:   from the European Union.
                    779:   It is copyrighted identically to a GNU software product, ie programme and
                    780:   software can be distributed freely for non commercial use. Latest version
                    781:   can be accessed at http://euroreves.ined.fr/imach .
                    782: 
                    783:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    784:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    785:   
                    786:   **********************************************************************/
                    787: /*
                    788:   main
                    789:   read parameterfile
                    790:   read datafile
                    791:   concatwav
                    792:   freqsummary
                    793:   if (mle >= 1)
                    794:     mlikeli
                    795:   print results files
                    796:   if mle==1 
                    797:      computes hessian
                    798:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    799:       begin-prev-date,...
                    800:   open gnuplot file
                    801:   open html file
1.145     brouard   802:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    803:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    804:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    805:     freexexit2 possible for memory heap.
                    806: 
                    807:   h Pij x                         | pij_nom  ficrestpij
                    808:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    809:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    810:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    811: 
                    812:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    813:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    814:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    815:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    816:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    817: 
1.126     brouard   818:   forecasting if prevfcast==1 prevforecast call prevalence()
                    819:   health expectancies
                    820:   Variance-covariance of DFLE
                    821:   prevalence()
                    822:    movingaverage()
                    823:   varevsij() 
                    824:   if popbased==1 varevsij(,popbased)
                    825:   total life expectancies
                    826:   Variance of period (stable) prevalence
                    827:  end
                    828: */
                    829: 
1.187     brouard   830: /* #define DEBUG */
                    831: /* #define DEBUGBRENT */
1.203     brouard   832: /* #define DEBUGLINMIN */
                    833: /* #define DEBUGHESS */
                    834: #define DEBUGHESSIJ
1.224     brouard   835: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   836: #define POWELL /* Instead of NLOPT */
1.224     brouard   837: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   838: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    839: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   840: 
                    841: #include <math.h>
                    842: #include <stdio.h>
                    843: #include <stdlib.h>
                    844: #include <string.h>
1.226     brouard   845: #include <ctype.h>
1.159     brouard   846: 
                    847: #ifdef _WIN32
                    848: #include <io.h>
1.172     brouard   849: #include <windows.h>
                    850: #include <tchar.h>
1.159     brouard   851: #else
1.126     brouard   852: #include <unistd.h>
1.159     brouard   853: #endif
1.126     brouard   854: 
                    855: #include <limits.h>
                    856: #include <sys/types.h>
1.171     brouard   857: 
                    858: #if defined(__GNUC__)
                    859: #include <sys/utsname.h> /* Doesn't work on Windows */
                    860: #endif
                    861: 
1.126     brouard   862: #include <sys/stat.h>
                    863: #include <errno.h>
1.159     brouard   864: /* extern int errno; */
1.126     brouard   865: 
1.157     brouard   866: /* #ifdef LINUX */
                    867: /* #include <time.h> */
                    868: /* #include "timeval.h" */
                    869: /* #else */
                    870: /* #include <sys/time.h> */
                    871: /* #endif */
                    872: 
1.126     brouard   873: #include <time.h>
                    874: 
1.136     brouard   875: #ifdef GSL
                    876: #include <gsl/gsl_errno.h>
                    877: #include <gsl/gsl_multimin.h>
                    878: #endif
                    879: 
1.167     brouard   880: 
1.162     brouard   881: #ifdef NLOPT
                    882: #include <nlopt.h>
                    883: typedef struct {
                    884:   double (* function)(double [] );
                    885: } myfunc_data ;
                    886: #endif
                    887: 
1.126     brouard   888: /* #include <libintl.h> */
                    889: /* #define _(String) gettext (String) */
                    890: 
1.141     brouard   891: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   892: 
                    893: #define GNUPLOTPROGRAM "gnuplot"
                    894: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    895: #define FILENAMELENGTH 132
                    896: 
                    897: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    898: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    899: 
1.144     brouard   900: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    901: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   902: 
                    903: #define NINTERVMAX 8
1.144     brouard   904: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    905: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    906: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   907: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   908: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    909: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   910: #define MAXN 20000
1.144     brouard   911: #define YEARM 12. /**< Number of months per year */
1.218     brouard   912: /* #define AGESUP 130 */
                    913: #define AGESUP 150
                    914: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   915: #define AGEBASE 40
1.194     brouard   916: #define AGEOVERFLOW 1.e20
1.164     brouard   917: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   918: #ifdef _WIN32
                    919: #define DIRSEPARATOR '\\'
                    920: #define CHARSEPARATOR "\\"
                    921: #define ODIRSEPARATOR '/'
                    922: #else
1.126     brouard   923: #define DIRSEPARATOR '/'
                    924: #define CHARSEPARATOR "/"
                    925: #define ODIRSEPARATOR '\\'
                    926: #endif
                    927: 
1.242   ! brouard   928: /* $Id: imach.c,v 1.241 2016/08/29 17:17:25 brouard Exp $ */
1.126     brouard   929: /* $State: Exp $ */
1.196     brouard   930: #include "version.h"
                    931: char version[]=__IMACH_VERSION__;
1.224     brouard   932: char copyright[]="February 2016,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2018";
1.242   ! brouard   933: char fullversion[]="$Revision: 1.241 $ $Date: 2016/08/29 17:17:25 $"; 
1.126     brouard   934: char strstart[80];
                    935: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   936: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   937: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   938: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    939: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    940: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   941: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    942: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   943: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    944: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    945: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   946: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    947: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   948: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   949: int nsd=0; /**< Total number of single dummy variables (output) */
                    950: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   951: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   952: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   953: int ntveff=0; /**< ntveff number of effective time varying variables */
                    954: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   955: int cptcov=0; /* Working variable */
1.218     brouard   956: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   957: int npar=NPARMAX;
                    958: int nlstate=2; /* Number of live states */
                    959: int ndeath=1; /* Number of dead states */
1.130     brouard   960: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   961: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   962: int popbased=0;
                    963: 
                    964: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   965: int maxwav=0; /* Maxim number of waves */
                    966: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    967: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    968: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   969:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   970: int mle=1, weightopt=0;
1.126     brouard   971: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    972: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    973: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    974:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   975: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   976: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    977: 
1.130     brouard   978: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   979: double **matprod2(); /* test */
1.126     brouard   980: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    981: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   982: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    983: 
1.136     brouard   984: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   985: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   986: FILE *ficlog, *ficrespow;
1.130     brouard   987: int globpr=0; /* Global variable for printing or not */
1.126     brouard   988: double fretone; /* Only one call to likelihood */
1.130     brouard   989: long ipmx=0; /* Number of contributions */
1.126     brouard   990: double sw; /* Sum of weights */
                    991: char filerespow[FILENAMELENGTH];
                    992: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    993: FILE *ficresilk;
                    994: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    995: FILE *ficresprobmorprev;
                    996: FILE *fichtm, *fichtmcov; /* Html File */
                    997: FILE *ficreseij;
                    998: char filerese[FILENAMELENGTH];
                    999: FILE *ficresstdeij;
                   1000: char fileresstde[FILENAMELENGTH];
                   1001: FILE *ficrescveij;
                   1002: char filerescve[FILENAMELENGTH];
                   1003: FILE  *ficresvij;
                   1004: char fileresv[FILENAMELENGTH];
                   1005: FILE  *ficresvpl;
                   1006: char fileresvpl[FILENAMELENGTH];
                   1007: char title[MAXLINE];
1.234     brouard  1008: char model[MAXLINE]; /**< The model line */
1.217     brouard  1009: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1010: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1011: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1012: char command[FILENAMELENGTH];
                   1013: int  outcmd=0;
                   1014: 
1.217     brouard  1015: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1016: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1017: char filelog[FILENAMELENGTH]; /* Log file */
                   1018: char filerest[FILENAMELENGTH];
                   1019: char fileregp[FILENAMELENGTH];
                   1020: char popfile[FILENAMELENGTH];
                   1021: 
                   1022: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1023: 
1.157     brouard  1024: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1025: /* struct timezone tzp; */
                   1026: /* extern int gettimeofday(); */
                   1027: struct tm tml, *gmtime(), *localtime();
                   1028: 
                   1029: extern time_t time();
                   1030: 
                   1031: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1032: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1033: struct tm tm;
                   1034: 
1.126     brouard  1035: char strcurr[80], strfor[80];
                   1036: 
                   1037: char *endptr;
                   1038: long lval;
                   1039: double dval;
                   1040: 
                   1041: #define NR_END 1
                   1042: #define FREE_ARG char*
                   1043: #define FTOL 1.0e-10
                   1044: 
                   1045: #define NRANSI 
1.240     brouard  1046: #define ITMAX 200
                   1047: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1048: 
                   1049: #define TOL 2.0e-4 
                   1050: 
                   1051: #define CGOLD 0.3819660 
                   1052: #define ZEPS 1.0e-10 
                   1053: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1054: 
                   1055: #define GOLD 1.618034 
                   1056: #define GLIMIT 100.0 
                   1057: #define TINY 1.0e-20 
                   1058: 
                   1059: static double maxarg1,maxarg2;
                   1060: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1061: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1062:   
                   1063: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1064: #define rint(a) floor(a+0.5)
1.166     brouard  1065: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1066: #define mytinydouble 1.0e-16
1.166     brouard  1067: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1068: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1069: /* static double dsqrarg; */
                   1070: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1071: static double sqrarg;
                   1072: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1073: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1074: int agegomp= AGEGOMP;
                   1075: 
                   1076: int imx; 
                   1077: int stepm=1;
                   1078: /* Stepm, step in month: minimum step interpolation*/
                   1079: 
                   1080: int estepm;
                   1081: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1082: 
                   1083: int m,nb;
                   1084: long *num;
1.197     brouard  1085: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1086: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1087:                   covariate for which somebody answered excluding 
                   1088:                   undefined. Usually 2: 0 and 1. */
                   1089: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1090:                             covariate for which somebody answered including 
                   1091:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1092: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1093: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1094: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1095: double *ageexmed,*agecens;
                   1096: double dateintmean=0;
                   1097: 
                   1098: double *weight;
                   1099: int **s; /* Status */
1.141     brouard  1100: double *agedc;
1.145     brouard  1101: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1102:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1103:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1104: double **coqvar; /* Fixed quantitative covariate iqv */
                   1105: double ***cotvar; /* Time varying covariate itv */
                   1106: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1107: double  idx; 
                   1108: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1109: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1110: /*k          1  2   3   4     5    6    7     8    9 */
                   1111: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1112: /* Tndvar[k]    1   2   3               4          5 */
                   1113: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1114: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1115: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1116: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1117: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1118: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1119: /* Tprod[i]=k           4               7            */
                   1120: /* Tage[i]=k                  5               8      */
                   1121: /* */
                   1122: /* Type                    */
                   1123: /* V         1  2  3  4  5 */
                   1124: /*           F  F  V  V  V */
                   1125: /*           D  Q  D  D  Q */
                   1126: /*                         */
                   1127: int *TvarsD;
                   1128: int *TvarsDind;
                   1129: int *TvarsQ;
                   1130: int *TvarsQind;
                   1131: 
1.235     brouard  1132: #define MAXRESULTLINES 10
                   1133: int nresult=0;
                   1134: int TKresult[MAXRESULTLINES];
1.237     brouard  1135: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1136: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1137: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1138: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1139: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1140: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1141: 
1.234     brouard  1142: /* 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  1143: 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 */
                   1144: 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 */
                   1145: 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 */
                   1146: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1147: 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 */
                   1148: 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  1149: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1150: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1151: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1152: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1153: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1154: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1155: 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 */
                   1156: 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 */
                   1157: 
1.230     brouard  1158: int *Tvarsel; /**< Selected covariates for output */
                   1159: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1160: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1161: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1162: 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  1163: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1164: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1165: int *Tage;
1.227     brouard  1166: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1167: 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  1168: 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*/ 
                   1169: 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  1170: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1171: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1172: int **Tvard;
                   1173: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1174: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1175: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1176:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1177:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1178: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1179: double *lsurv, *lpop, *tpop;
                   1180: 
1.231     brouard  1181: #define FD 1; /* Fixed dummy covariate */
                   1182: #define FQ 2; /* Fixed quantitative covariate */
                   1183: #define FP 3; /* Fixed product covariate */
                   1184: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1185: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1186: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1187: #define VD 10; /* Varying dummy covariate */
                   1188: #define VQ 11; /* Varying quantitative covariate */
                   1189: #define VP 12; /* Varying product covariate */
                   1190: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1191: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1192: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1193: #define APFD 16; /* Age product * fixed dummy covariate */
                   1194: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1195: #define APVD 18; /* Age product * varying dummy covariate */
                   1196: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1197: 
                   1198: #define FTYPE 1; /* Fixed covariate */
                   1199: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1200: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1201: 
                   1202: struct kmodel{
                   1203:        int maintype; /* main type */
                   1204:        int subtype; /* subtype */
                   1205: };
                   1206: struct kmodel modell[NCOVMAX];
                   1207: 
1.143     brouard  1208: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1209: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1210: 
                   1211: /**************** split *************************/
                   1212: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1213: {
                   1214:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1215:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1216:   */ 
                   1217:   char *ss;                            /* pointer */
1.186     brouard  1218:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1219: 
                   1220:   l1 = strlen(path );                  /* length of path */
                   1221:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1222:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1223:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1224:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1225:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1226:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1227:     /* get current working directory */
                   1228:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1229: #ifdef WIN32
                   1230:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1231: #else
                   1232:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1233: #endif
1.126     brouard  1234:       return( GLOCK_ERROR_GETCWD );
                   1235:     }
                   1236:     /* got dirc from getcwd*/
                   1237:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1238:   } else {                             /* strip directory from path */
1.126     brouard  1239:     ss++;                              /* after this, the filename */
                   1240:     l2 = strlen( ss );                 /* length of filename */
                   1241:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1242:     strcpy( name, ss );                /* save file name */
                   1243:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1244:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1245:     printf(" DIRC2 = %s \n",dirc);
                   1246:   }
                   1247:   /* We add a separator at the end of dirc if not exists */
                   1248:   l1 = strlen( dirc );                 /* length of directory */
                   1249:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1250:     dirc[l1] =  DIRSEPARATOR;
                   1251:     dirc[l1+1] = 0; 
                   1252:     printf(" DIRC3 = %s \n",dirc);
                   1253:   }
                   1254:   ss = strrchr( name, '.' );           /* find last / */
                   1255:   if (ss >0){
                   1256:     ss++;
                   1257:     strcpy(ext,ss);                    /* save extension */
                   1258:     l1= strlen( name);
                   1259:     l2= strlen(ss)+1;
                   1260:     strncpy( finame, name, l1-l2);
                   1261:     finame[l1-l2]= 0;
                   1262:   }
                   1263: 
                   1264:   return( 0 );                         /* we're done */
                   1265: }
                   1266: 
                   1267: 
                   1268: /******************************************/
                   1269: 
                   1270: void replace_back_to_slash(char *s, char*t)
                   1271: {
                   1272:   int i;
                   1273:   int lg=0;
                   1274:   i=0;
                   1275:   lg=strlen(t);
                   1276:   for(i=0; i<= lg; i++) {
                   1277:     (s[i] = t[i]);
                   1278:     if (t[i]== '\\') s[i]='/';
                   1279:   }
                   1280: }
                   1281: 
1.132     brouard  1282: char *trimbb(char *out, char *in)
1.137     brouard  1283: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1284:   char *s;
                   1285:   s=out;
                   1286:   while (*in != '\0'){
1.137     brouard  1287:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1288:       in++;
                   1289:     }
                   1290:     *out++ = *in++;
                   1291:   }
                   1292:   *out='\0';
                   1293:   return s;
                   1294: }
                   1295: 
1.187     brouard  1296: /* char *substrchaine(char *out, char *in, char *chain) */
                   1297: /* { */
                   1298: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1299: /*   char *s, *t; */
                   1300: /*   t=in;s=out; */
                   1301: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1302: /*     *out++ = *in++; */
                   1303: /*   } */
                   1304: 
                   1305: /*   /\* *in matches *chain *\/ */
                   1306: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1307: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1308: /*   } */
                   1309: /*   in--; chain--; */
                   1310: /*   while ( (*in != '\0')){ */
                   1311: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1312: /*     *out++ = *in++; */
                   1313: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1314: /*   } */
                   1315: /*   *out='\0'; */
                   1316: /*   out=s; */
                   1317: /*   return out; */
                   1318: /* } */
                   1319: char *substrchaine(char *out, char *in, char *chain)
                   1320: {
                   1321:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1322:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1323: 
                   1324:   char *strloc;
                   1325: 
                   1326:   strcpy (out, in); 
                   1327:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1328:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1329:   if(strloc != NULL){ 
                   1330:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1331:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1332:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1333:   }
                   1334:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1335:   return out;
                   1336: }
                   1337: 
                   1338: 
1.145     brouard  1339: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1340: {
1.187     brouard  1341:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1342:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1343:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1344:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1345:   */
1.160     brouard  1346:   char *s, *t;
1.145     brouard  1347:   t=in;s=in;
                   1348:   while ((*in != occ) && (*in != '\0')){
                   1349:     *alocc++ = *in++;
                   1350:   }
                   1351:   if( *in == occ){
                   1352:     *(alocc)='\0';
                   1353:     s=++in;
                   1354:   }
                   1355:  
                   1356:   if (s == t) {/* occ not found */
                   1357:     *(alocc-(in-s))='\0';
                   1358:     in=s;
                   1359:   }
                   1360:   while ( *in != '\0'){
                   1361:     *blocc++ = *in++;
                   1362:   }
                   1363: 
                   1364:   *blocc='\0';
                   1365:   return t;
                   1366: }
1.137     brouard  1367: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1368: {
1.187     brouard  1369:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1370:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1371:      gives blocc="abcdef2ghi" and alocc="j".
                   1372:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1373:   */
                   1374:   char *s, *t;
                   1375:   t=in;s=in;
                   1376:   while (*in != '\0'){
                   1377:     while( *in == occ){
                   1378:       *blocc++ = *in++;
                   1379:       s=in;
                   1380:     }
                   1381:     *blocc++ = *in++;
                   1382:   }
                   1383:   if (s == t) /* occ not found */
                   1384:     *(blocc-(in-s))='\0';
                   1385:   else
                   1386:     *(blocc-(in-s)-1)='\0';
                   1387:   in=s;
                   1388:   while ( *in != '\0'){
                   1389:     *alocc++ = *in++;
                   1390:   }
                   1391: 
                   1392:   *alocc='\0';
                   1393:   return s;
                   1394: }
                   1395: 
1.126     brouard  1396: int nbocc(char *s, char occ)
                   1397: {
                   1398:   int i,j=0;
                   1399:   int lg=20;
                   1400:   i=0;
                   1401:   lg=strlen(s);
                   1402:   for(i=0; i<= lg; i++) {
1.234     brouard  1403:     if  (s[i] == occ ) j++;
1.126     brouard  1404:   }
                   1405:   return j;
                   1406: }
                   1407: 
1.137     brouard  1408: /* void cutv(char *u,char *v, char*t, char occ) */
                   1409: /* { */
                   1410: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1411: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1412: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1413: /*   int i,lg,j,p=0; */
                   1414: /*   i=0; */
                   1415: /*   lg=strlen(t); */
                   1416: /*   for(j=0; j<=lg-1; j++) { */
                   1417: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1418: /*   } */
1.126     brouard  1419: 
1.137     brouard  1420: /*   for(j=0; j<p; j++) { */
                   1421: /*     (u[j] = t[j]); */
                   1422: /*   } */
                   1423: /*      u[p]='\0'; */
1.126     brouard  1424: 
1.137     brouard  1425: /*    for(j=0; j<= lg; j++) { */
                   1426: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1427: /*   } */
                   1428: /* } */
1.126     brouard  1429: 
1.160     brouard  1430: #ifdef _WIN32
                   1431: char * strsep(char **pp, const char *delim)
                   1432: {
                   1433:   char *p, *q;
                   1434:          
                   1435:   if ((p = *pp) == NULL)
                   1436:     return 0;
                   1437:   if ((q = strpbrk (p, delim)) != NULL)
                   1438:   {
                   1439:     *pp = q + 1;
                   1440:     *q = '\0';
                   1441:   }
                   1442:   else
                   1443:     *pp = 0;
                   1444:   return p;
                   1445: }
                   1446: #endif
                   1447: 
1.126     brouard  1448: /********************** nrerror ********************/
                   1449: 
                   1450: void nrerror(char error_text[])
                   1451: {
                   1452:   fprintf(stderr,"ERREUR ...\n");
                   1453:   fprintf(stderr,"%s\n",error_text);
                   1454:   exit(EXIT_FAILURE);
                   1455: }
                   1456: /*********************** vector *******************/
                   1457: double *vector(int nl, int nh)
                   1458: {
                   1459:   double *v;
                   1460:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1461:   if (!v) nrerror("allocation failure in vector");
                   1462:   return v-nl+NR_END;
                   1463: }
                   1464: 
                   1465: /************************ free vector ******************/
                   1466: void free_vector(double*v, int nl, int nh)
                   1467: {
                   1468:   free((FREE_ARG)(v+nl-NR_END));
                   1469: }
                   1470: 
                   1471: /************************ivector *******************************/
                   1472: int *ivector(long nl,long nh)
                   1473: {
                   1474:   int *v;
                   1475:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1476:   if (!v) nrerror("allocation failure in ivector");
                   1477:   return v-nl+NR_END;
                   1478: }
                   1479: 
                   1480: /******************free ivector **************************/
                   1481: void free_ivector(int *v, long nl, long nh)
                   1482: {
                   1483:   free((FREE_ARG)(v+nl-NR_END));
                   1484: }
                   1485: 
                   1486: /************************lvector *******************************/
                   1487: long *lvector(long nl,long nh)
                   1488: {
                   1489:   long *v;
                   1490:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1491:   if (!v) nrerror("allocation failure in ivector");
                   1492:   return v-nl+NR_END;
                   1493: }
                   1494: 
                   1495: /******************free lvector **************************/
                   1496: void free_lvector(long *v, long nl, long nh)
                   1497: {
                   1498:   free((FREE_ARG)(v+nl-NR_END));
                   1499: }
                   1500: 
                   1501: /******************* imatrix *******************************/
                   1502: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1503:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1504: { 
                   1505:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1506:   int **m; 
                   1507:   
                   1508:   /* allocate pointers to rows */ 
                   1509:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1510:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1511:   m += NR_END; 
                   1512:   m -= nrl; 
                   1513:   
                   1514:   
                   1515:   /* allocate rows and set pointers to them */ 
                   1516:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1517:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1518:   m[nrl] += NR_END; 
                   1519:   m[nrl] -= ncl; 
                   1520:   
                   1521:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1522:   
                   1523:   /* return pointer to array of pointers to rows */ 
                   1524:   return m; 
                   1525: } 
                   1526: 
                   1527: /****************** free_imatrix *************************/
                   1528: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1529:       int **m;
                   1530:       long nch,ncl,nrh,nrl; 
                   1531:      /* free an int matrix allocated by imatrix() */ 
                   1532: { 
                   1533:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1534:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1535: } 
                   1536: 
                   1537: /******************* matrix *******************************/
                   1538: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1539: {
                   1540:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1541:   double **m;
                   1542: 
                   1543:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1544:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1545:   m += NR_END;
                   1546:   m -= nrl;
                   1547: 
                   1548:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1549:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1550:   m[nrl] += NR_END;
                   1551:   m[nrl] -= ncl;
                   1552: 
                   1553:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1554:   return m;
1.145     brouard  1555:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1556: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1557: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1558:    */
                   1559: }
                   1560: 
                   1561: /*************************free matrix ************************/
                   1562: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1563: {
                   1564:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1565:   free((FREE_ARG)(m+nrl-NR_END));
                   1566: }
                   1567: 
                   1568: /******************* ma3x *******************************/
                   1569: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1570: {
                   1571:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1572:   double ***m;
                   1573: 
                   1574:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1575:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1576:   m += NR_END;
                   1577:   m -= nrl;
                   1578: 
                   1579:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1580:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1581:   m[nrl] += NR_END;
                   1582:   m[nrl] -= ncl;
                   1583: 
                   1584:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1585: 
                   1586:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1587:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1588:   m[nrl][ncl] += NR_END;
                   1589:   m[nrl][ncl] -= nll;
                   1590:   for (j=ncl+1; j<=nch; j++) 
                   1591:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1592:   
                   1593:   for (i=nrl+1; i<=nrh; i++) {
                   1594:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1595:     for (j=ncl+1; j<=nch; j++) 
                   1596:       m[i][j]=m[i][j-1]+nlay;
                   1597:   }
                   1598:   return m; 
                   1599:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1600:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1601:   */
                   1602: }
                   1603: 
                   1604: /*************************free ma3x ************************/
                   1605: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1606: {
                   1607:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1608:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1609:   free((FREE_ARG)(m+nrl-NR_END));
                   1610: }
                   1611: 
                   1612: /*************** function subdirf ***********/
                   1613: char *subdirf(char fileres[])
                   1614: {
                   1615:   /* Caution optionfilefiname is hidden */
                   1616:   strcpy(tmpout,optionfilefiname);
                   1617:   strcat(tmpout,"/"); /* Add to the right */
                   1618:   strcat(tmpout,fileres);
                   1619:   return tmpout;
                   1620: }
                   1621: 
                   1622: /*************** function subdirf2 ***********/
                   1623: char *subdirf2(char fileres[], char *preop)
                   1624: {
                   1625:   
                   1626:   /* Caution optionfilefiname is hidden */
                   1627:   strcpy(tmpout,optionfilefiname);
                   1628:   strcat(tmpout,"/");
                   1629:   strcat(tmpout,preop);
                   1630:   strcat(tmpout,fileres);
                   1631:   return tmpout;
                   1632: }
                   1633: 
                   1634: /*************** function subdirf3 ***********/
                   1635: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1636: {
                   1637:   
                   1638:   /* Caution optionfilefiname is hidden */
                   1639:   strcpy(tmpout,optionfilefiname);
                   1640:   strcat(tmpout,"/");
                   1641:   strcat(tmpout,preop);
                   1642:   strcat(tmpout,preop2);
                   1643:   strcat(tmpout,fileres);
                   1644:   return tmpout;
                   1645: }
1.213     brouard  1646:  
                   1647: /*************** function subdirfext ***********/
                   1648: char *subdirfext(char fileres[], char *preop, char *postop)
                   1649: {
                   1650:   
                   1651:   strcpy(tmpout,preop);
                   1652:   strcat(tmpout,fileres);
                   1653:   strcat(tmpout,postop);
                   1654:   return tmpout;
                   1655: }
1.126     brouard  1656: 
1.213     brouard  1657: /*************** function subdirfext3 ***********/
                   1658: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1659: {
                   1660:   
                   1661:   /* Caution optionfilefiname is hidden */
                   1662:   strcpy(tmpout,optionfilefiname);
                   1663:   strcat(tmpout,"/");
                   1664:   strcat(tmpout,preop);
                   1665:   strcat(tmpout,fileres);
                   1666:   strcat(tmpout,postop);
                   1667:   return tmpout;
                   1668: }
                   1669:  
1.162     brouard  1670: char *asc_diff_time(long time_sec, char ascdiff[])
                   1671: {
                   1672:   long sec_left, days, hours, minutes;
                   1673:   days = (time_sec) / (60*60*24);
                   1674:   sec_left = (time_sec) % (60*60*24);
                   1675:   hours = (sec_left) / (60*60) ;
                   1676:   sec_left = (sec_left) %(60*60);
                   1677:   minutes = (sec_left) /60;
                   1678:   sec_left = (sec_left) % (60);
                   1679:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1680:   return ascdiff;
                   1681: }
                   1682: 
1.126     brouard  1683: /***************** f1dim *************************/
                   1684: extern int ncom; 
                   1685: extern double *pcom,*xicom;
                   1686: extern double (*nrfunc)(double []); 
                   1687:  
                   1688: double f1dim(double x) 
                   1689: { 
                   1690:   int j; 
                   1691:   double f;
                   1692:   double *xt; 
                   1693:  
                   1694:   xt=vector(1,ncom); 
                   1695:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1696:   f=(*nrfunc)(xt); 
                   1697:   free_vector(xt,1,ncom); 
                   1698:   return f; 
                   1699: } 
                   1700: 
                   1701: /*****************brent *************************/
                   1702: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1703: {
                   1704:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1705:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1706:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1707:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1708:    * returned function value. 
                   1709:   */
1.126     brouard  1710:   int iter; 
                   1711:   double a,b,d,etemp;
1.159     brouard  1712:   double fu=0,fv,fw,fx;
1.164     brouard  1713:   double ftemp=0.;
1.126     brouard  1714:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1715:   double e=0.0; 
                   1716:  
                   1717:   a=(ax < cx ? ax : cx); 
                   1718:   b=(ax > cx ? ax : cx); 
                   1719:   x=w=v=bx; 
                   1720:   fw=fv=fx=(*f)(x); 
                   1721:   for (iter=1;iter<=ITMAX;iter++) { 
                   1722:     xm=0.5*(a+b); 
                   1723:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1724:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1725:     printf(".");fflush(stdout);
                   1726:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1727: #ifdef DEBUGBRENT
1.126     brouard  1728:     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);
                   1729:     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);
                   1730:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1731: #endif
                   1732:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1733:       *xmin=x; 
                   1734:       return fx; 
                   1735:     } 
                   1736:     ftemp=fu;
                   1737:     if (fabs(e) > tol1) { 
                   1738:       r=(x-w)*(fx-fv); 
                   1739:       q=(x-v)*(fx-fw); 
                   1740:       p=(x-v)*q-(x-w)*r; 
                   1741:       q=2.0*(q-r); 
                   1742:       if (q > 0.0) p = -p; 
                   1743:       q=fabs(q); 
                   1744:       etemp=e; 
                   1745:       e=d; 
                   1746:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1747:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1748:       else { 
1.224     brouard  1749:                                d=p/q; 
                   1750:                                u=x+d; 
                   1751:                                if (u-a < tol2 || b-u < tol2) 
                   1752:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1753:       } 
                   1754:     } else { 
                   1755:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1756:     } 
                   1757:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1758:     fu=(*f)(u); 
                   1759:     if (fu <= fx) { 
                   1760:       if (u >= x) a=x; else b=x; 
                   1761:       SHFT(v,w,x,u) 
1.183     brouard  1762:       SHFT(fv,fw,fx,fu) 
                   1763:     } else { 
                   1764:       if (u < x) a=u; else b=u; 
                   1765:       if (fu <= fw || w == x) { 
1.224     brouard  1766:                                v=w; 
                   1767:                                w=u; 
                   1768:                                fv=fw; 
                   1769:                                fw=fu; 
1.183     brouard  1770:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1771:                                v=u; 
                   1772:                                fv=fu; 
1.183     brouard  1773:       } 
                   1774:     } 
1.126     brouard  1775:   } 
                   1776:   nrerror("Too many iterations in brent"); 
                   1777:   *xmin=x; 
                   1778:   return fx; 
                   1779: } 
                   1780: 
                   1781: /****************** mnbrak ***********************/
                   1782: 
                   1783: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1784:            double (*func)(double)) 
1.183     brouard  1785: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1786: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1787: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1788: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1789:    */
1.126     brouard  1790:   double ulim,u,r,q, dum;
                   1791:   double fu; 
1.187     brouard  1792: 
                   1793:   double scale=10.;
                   1794:   int iterscale=0;
                   1795: 
                   1796:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1797:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1798: 
                   1799: 
                   1800:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1801:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1802:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1803:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1804:   /* } */
                   1805: 
1.126     brouard  1806:   if (*fb > *fa) { 
                   1807:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1808:     SHFT(dum,*fb,*fa,dum) 
                   1809:   } 
1.126     brouard  1810:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1811:   *fc=(*func)(*cx); 
1.183     brouard  1812: #ifdef DEBUG
1.224     brouard  1813:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1814:   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  1815: #endif
1.224     brouard  1816:   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  1817:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1818:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1819:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1820:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1821:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1822:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1823:       fu=(*func)(u); 
1.163     brouard  1824: #ifdef DEBUG
                   1825:       /* f(x)=A(x-u)**2+f(u) */
                   1826:       double A, fparabu; 
                   1827:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1828:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1829:       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);
                   1830:       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  1831:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1832:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1833:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1834:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1835: #endif 
1.184     brouard  1836: #ifdef MNBRAKORIGINAL
1.183     brouard  1837: #else
1.191     brouard  1838: /*       if (fu > *fc) { */
                   1839: /* #ifdef DEBUG */
                   1840: /*       printf("mnbrak4  fu > fc \n"); */
                   1841: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1842: /* #endif */
                   1843: /*     /\* 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 *\\/  *\/ */
                   1844: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1845: /*     dum=u; /\* Shifting c and u *\/ */
                   1846: /*     u = *cx; */
                   1847: /*     *cx = dum; */
                   1848: /*     dum = fu; */
                   1849: /*     fu = *fc; */
                   1850: /*     *fc =dum; */
                   1851: /*       } else { /\* end *\/ */
                   1852: /* #ifdef DEBUG */
                   1853: /*       printf("mnbrak3  fu < fc \n"); */
                   1854: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1855: /* #endif */
                   1856: /*     dum=u; /\* Shifting c and u *\/ */
                   1857: /*     u = *cx; */
                   1858: /*     *cx = dum; */
                   1859: /*     dum = fu; */
                   1860: /*     fu = *fc; */
                   1861: /*     *fc =dum; */
                   1862: /*       } */
1.224     brouard  1863: #ifdef DEBUGMNBRAK
                   1864:                 double A, fparabu; 
                   1865:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1866:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1867:      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);
                   1868:      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  1869: #endif
1.191     brouard  1870:       dum=u; /* Shifting c and u */
                   1871:       u = *cx;
                   1872:       *cx = dum;
                   1873:       dum = fu;
                   1874:       fu = *fc;
                   1875:       *fc =dum;
1.183     brouard  1876: #endif
1.162     brouard  1877:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1878: #ifdef DEBUG
1.224     brouard  1879:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1880:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1881: #endif
1.126     brouard  1882:       fu=(*func)(u); 
                   1883:       if (fu < *fc) { 
1.183     brouard  1884: #ifdef DEBUG
1.224     brouard  1885:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1886:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1887: #endif
                   1888:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1889:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1890: #ifdef DEBUG
                   1891:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1892: #endif
                   1893:       } 
1.162     brouard  1894:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1895: #ifdef DEBUG
1.224     brouard  1896:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1897:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1898: #endif
1.126     brouard  1899:       u=ulim; 
                   1900:       fu=(*func)(u); 
1.183     brouard  1901:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1902: #ifdef DEBUG
1.224     brouard  1903:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1904:       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  1905: #endif
1.126     brouard  1906:       u=(*cx)+GOLD*(*cx-*bx); 
                   1907:       fu=(*func)(u); 
1.224     brouard  1908: #ifdef DEBUG
                   1909:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1910:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1911: #endif
1.183     brouard  1912:     } /* end tests */
1.126     brouard  1913:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1914:     SHFT(*fa,*fb,*fc,fu) 
                   1915: #ifdef DEBUG
1.224     brouard  1916:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1917:       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  1918: #endif
                   1919:   } /* 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  1920: } 
                   1921: 
                   1922: /*************** linmin ************************/
1.162     brouard  1923: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1924: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1925: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1926: the value of func at the returned location p . This is actually all accomplished by calling the
                   1927: routines mnbrak and brent .*/
1.126     brouard  1928: int ncom; 
                   1929: double *pcom,*xicom;
                   1930: double (*nrfunc)(double []); 
                   1931:  
1.224     brouard  1932: #ifdef LINMINORIGINAL
1.126     brouard  1933: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1934: #else
                   1935: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1936: #endif
1.126     brouard  1937: { 
                   1938:   double brent(double ax, double bx, double cx, 
                   1939:               double (*f)(double), double tol, double *xmin); 
                   1940:   double f1dim(double x); 
                   1941:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1942:              double *fc, double (*func)(double)); 
                   1943:   int j; 
                   1944:   double xx,xmin,bx,ax; 
                   1945:   double fx,fb,fa;
1.187     brouard  1946: 
1.203     brouard  1947: #ifdef LINMINORIGINAL
                   1948: #else
                   1949:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1950: #endif
                   1951:   
1.126     brouard  1952:   ncom=n; 
                   1953:   pcom=vector(1,n); 
                   1954:   xicom=vector(1,n); 
                   1955:   nrfunc=func; 
                   1956:   for (j=1;j<=n;j++) { 
                   1957:     pcom[j]=p[j]; 
1.202     brouard  1958:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1959:   } 
1.187     brouard  1960: 
1.203     brouard  1961: #ifdef LINMINORIGINAL
                   1962:   xx=1.;
                   1963: #else
                   1964:   axs=0.0;
                   1965:   xxs=1.;
                   1966:   do{
                   1967:     xx= xxs;
                   1968: #endif
1.187     brouard  1969:     ax=0.;
                   1970:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1971:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1972:     /* 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))   */
                   1973:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1974:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1975:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1976:     /* 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  1977: #ifdef LINMINORIGINAL
                   1978: #else
                   1979:     if (fx != fx){
1.224     brouard  1980:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1981:                        printf("|");
                   1982:                        fprintf(ficlog,"|");
1.203     brouard  1983: #ifdef DEBUGLINMIN
1.224     brouard  1984:                        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  1985: #endif
                   1986:     }
1.224     brouard  1987:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1988: #endif
                   1989:   
1.191     brouard  1990: #ifdef DEBUGLINMIN
                   1991:   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  1992:   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  1993: #endif
1.224     brouard  1994: #ifdef LINMINORIGINAL
                   1995: #else
                   1996:        if(fb == fx){ /* Flat function in the direction */
                   1997:                xmin=xx;
                   1998:     *flat=1;
                   1999:        }else{
                   2000:     *flat=0;
                   2001: #endif
                   2002:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2003:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2004:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2005:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2006:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2007:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2008: #ifdef DEBUG
1.224     brouard  2009:   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);
                   2010:   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);
                   2011: #endif
                   2012: #ifdef LINMINORIGINAL
                   2013: #else
                   2014:                        }
1.126     brouard  2015: #endif
1.191     brouard  2016: #ifdef DEBUGLINMIN
                   2017:   printf("linmin end ");
1.202     brouard  2018:   fprintf(ficlog,"linmin end ");
1.191     brouard  2019: #endif
1.126     brouard  2020:   for (j=1;j<=n;j++) { 
1.203     brouard  2021: #ifdef LINMINORIGINAL
                   2022:     xi[j] *= xmin; 
                   2023: #else
                   2024: #ifdef DEBUGLINMIN
                   2025:     if(xxs <1.0)
                   2026:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2027: #endif
                   2028:     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) */
                   2029: #ifdef DEBUGLINMIN
                   2030:     if(xxs <1.0)
                   2031:       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 );
                   2032: #endif
                   2033: #endif
1.187     brouard  2034:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2035:   } 
1.191     brouard  2036: #ifdef DEBUGLINMIN
1.203     brouard  2037:   printf("\n");
1.191     brouard  2038:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2039:   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  2040:   for (j=1;j<=n;j++) { 
1.202     brouard  2041:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2042:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2043:     if(j % ncovmodel == 0){
1.191     brouard  2044:       printf("\n");
1.202     brouard  2045:       fprintf(ficlog,"\n");
                   2046:     }
1.191     brouard  2047:   }
1.203     brouard  2048: #else
1.191     brouard  2049: #endif
1.126     brouard  2050:   free_vector(xicom,1,n); 
                   2051:   free_vector(pcom,1,n); 
                   2052: } 
                   2053: 
                   2054: 
                   2055: /*************** powell ************************/
1.162     brouard  2056: /*
                   2057: Minimization of a function func of n variables. Input consists of an initial starting point
                   2058: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2059: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2060: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2061: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2062: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2063:  */
1.224     brouard  2064: #ifdef LINMINORIGINAL
                   2065: #else
                   2066:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2067:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2068: #endif
1.126     brouard  2069: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2070:            double (*func)(double [])) 
                   2071: { 
1.224     brouard  2072: #ifdef LINMINORIGINAL
                   2073:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2074:              double (*func)(double [])); 
1.224     brouard  2075: #else 
1.241     brouard  2076:  void linmin(double p[], double xi[], int n, double *fret,
                   2077:             double (*func)(double []),int *flat); 
1.224     brouard  2078: #endif
1.239     brouard  2079:  int i,ibig,j,jk,k; 
1.126     brouard  2080:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2081:   double directest;
1.126     brouard  2082:   double fp,fptt;
                   2083:   double *xits;
                   2084:   int niterf, itmp;
1.224     brouard  2085: #ifdef LINMINORIGINAL
                   2086: #else
                   2087: 
                   2088:   flatdir=ivector(1,n); 
                   2089:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2090: #endif
1.126     brouard  2091: 
                   2092:   pt=vector(1,n); 
                   2093:   ptt=vector(1,n); 
                   2094:   xit=vector(1,n); 
                   2095:   xits=vector(1,n); 
                   2096:   *fret=(*func)(p); 
                   2097:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2098:   rcurr_time = time(NULL);  
1.126     brouard  2099:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2100:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2101:     ibig=0; 
                   2102:     del=0.0; 
1.157     brouard  2103:     rlast_time=rcurr_time;
                   2104:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2105:     rcurr_time = time(NULL);  
                   2106:     curr_time = *localtime(&rcurr_time);
                   2107:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2108:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2109: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2110:     for (i=1;i<=n;i++) {
1.126     brouard  2111:       fprintf(ficrespow," %.12lf", p[i]);
                   2112:     }
1.239     brouard  2113:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2114:     printf("\n#model=  1      +     age ");
                   2115:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2116:     if(nagesqr==1){
1.241     brouard  2117:        printf("  + age*age  ");
                   2118:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2119:     }
                   2120:     for(j=1;j <=ncovmodel-2;j++){
                   2121:       if(Typevar[j]==0) {
                   2122:        printf("  +      V%d  ",Tvar[j]);
                   2123:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2124:       }else if(Typevar[j]==1) {
                   2125:        printf("  +    V%d*age ",Tvar[j]);
                   2126:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2127:       }else if(Typevar[j]==2) {
                   2128:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2129:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2130:       }
                   2131:     }
1.126     brouard  2132:     printf("\n");
1.239     brouard  2133: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2134: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2135:     fprintf(ficlog,"\n");
1.239     brouard  2136:     for(i=1,jk=1; i <=nlstate; i++){
                   2137:       for(k=1; k <=(nlstate+ndeath); k++){
                   2138:        if (k != i) {
                   2139:          printf("%d%d ",i,k);
                   2140:          fprintf(ficlog,"%d%d ",i,k);
                   2141:          for(j=1; j <=ncovmodel; j++){
                   2142:            printf("%12.7f ",p[jk]);
                   2143:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2144:            jk++; 
                   2145:          }
                   2146:          printf("\n");
                   2147:          fprintf(ficlog,"\n");
                   2148:        }
                   2149:       }
                   2150:     }
1.241     brouard  2151:     if(*iter <=3 && *iter >1){
1.157     brouard  2152:       tml = *localtime(&rcurr_time);
                   2153:       strcpy(strcurr,asctime(&tml));
                   2154:       rforecast_time=rcurr_time; 
1.126     brouard  2155:       itmp = strlen(strcurr);
                   2156:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2157:        strcurr[itmp-1]='\0';
1.162     brouard  2158:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2159:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2160:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2161:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2162:        forecast_time = *localtime(&rforecast_time);
                   2163:        strcpy(strfor,asctime(&forecast_time));
                   2164:        itmp = strlen(strfor);
                   2165:        if(strfor[itmp-1]=='\n')
                   2166:          strfor[itmp-1]='\0';
                   2167:        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);
                   2168:        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  2169:       }
                   2170:     }
1.187     brouard  2171:     for (i=1;i<=n;i++) { /* For each direction i */
                   2172:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2173:       fptt=(*fret); 
                   2174: #ifdef DEBUG
1.203     brouard  2175:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2176:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2177: #endif
1.203     brouard  2178:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2179:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2180: #ifdef LINMINORIGINAL
1.188     brouard  2181:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2182: #else
                   2183:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2184:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2185: #endif
                   2186:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2187:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2188:                                /* because that direction will be replaced unless the gain del is small */
                   2189:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2190:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2191:                                /* with the new direction. */
                   2192:                                del=fabs(fptt-(*fret)); 
                   2193:                                ibig=i; 
1.126     brouard  2194:       } 
                   2195: #ifdef DEBUG
                   2196:       printf("%d %.12e",i,(*fret));
                   2197:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2198:       for (j=1;j<=n;j++) {
1.224     brouard  2199:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2200:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2201:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2202:       }
                   2203:       for(j=1;j<=n;j++) {
1.225     brouard  2204:                                printf(" p(%d)=%.12e",j,p[j]);
                   2205:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2206:       }
                   2207:       printf("\n");
                   2208:       fprintf(ficlog,"\n");
                   2209: #endif
1.187     brouard  2210:     } /* end loop on each direction i */
                   2211:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2212:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2213:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2214:       for(j=1;j<=n;j++) {
1.225     brouard  2215:                                if(flatdir[j] >0){
                   2216:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2217:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2218:                                }
                   2219:                                /* printf("\n"); */
                   2220:                                /* fprintf(ficlog,"\n"); */
                   2221:                        }
1.182     brouard  2222:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  2223:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2224:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2225:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2226:       /* decreased of more than 3.84  */
                   2227:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2228:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2229:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2230:                        
1.188     brouard  2231:       /* Starting the program with initial values given by a former maximization will simply change */
                   2232:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2233:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2234:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2235: #ifdef DEBUG
                   2236:       int k[2],l;
                   2237:       k[0]=1;
                   2238:       k[1]=-1;
                   2239:       printf("Max: %.12e",(*func)(p));
                   2240:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2241:       for (j=1;j<=n;j++) {
                   2242:        printf(" %.12e",p[j]);
                   2243:        fprintf(ficlog," %.12e",p[j]);
                   2244:       }
                   2245:       printf("\n");
                   2246:       fprintf(ficlog,"\n");
                   2247:       for(l=0;l<=1;l++) {
                   2248:        for (j=1;j<=n;j++) {
                   2249:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2250:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2251:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2252:        }
                   2253:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2254:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2255:       }
                   2256: #endif
                   2257: 
1.224     brouard  2258: #ifdef LINMINORIGINAL
                   2259: #else
                   2260:       free_ivector(flatdir,1,n); 
                   2261: #endif
1.126     brouard  2262:       free_vector(xit,1,n); 
                   2263:       free_vector(xits,1,n); 
                   2264:       free_vector(ptt,1,n); 
                   2265:       free_vector(pt,1,n); 
                   2266:       return; 
1.192     brouard  2267:     } /* enough precision */ 
1.240     brouard  2268:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2269:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2270:       ptt[j]=2.0*p[j]-pt[j]; 
                   2271:       xit[j]=p[j]-pt[j]; 
                   2272:       pt[j]=p[j]; 
                   2273:     } 
1.181     brouard  2274:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2275: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2276:                if (*iter <=4) {
1.225     brouard  2277: #else
                   2278: #endif
1.224     brouard  2279: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2280: #else
1.161     brouard  2281:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2282: #endif
1.162     brouard  2283:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2284:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2285:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2286:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2287:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2288:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2289:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2290:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2291:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2292:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2293:       /* mu² and del² are equal when f3=f1 */
                   2294:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2295:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2296:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2297:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2298: #ifdef NRCORIGINAL
                   2299:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2300: #else
                   2301:       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  2302:       t= t- del*SQR(fp-fptt);
1.183     brouard  2303: #endif
1.202     brouard  2304:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2305: #ifdef DEBUG
1.181     brouard  2306:       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);
                   2307:       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  2308:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2309:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2310:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2311:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2312:       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);
                   2313:       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);
                   2314: #endif
1.183     brouard  2315: #ifdef POWELLORIGINAL
                   2316:       if (t < 0.0) { /* Then we use it for new direction */
                   2317: #else
1.182     brouard  2318:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2319:                                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  2320:         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  2321:         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  2322:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2323:       } 
1.181     brouard  2324:       if (directest < 0.0) { /* Then we use it for new direction */
                   2325: #endif
1.191     brouard  2326: #ifdef DEBUGLINMIN
1.234     brouard  2327:        printf("Before linmin in direction P%d-P0\n",n);
                   2328:        for (j=1;j<=n;j++) {
                   2329:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2330:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2331:          if(j % ncovmodel == 0){
                   2332:            printf("\n");
                   2333:            fprintf(ficlog,"\n");
                   2334:          }
                   2335:        }
1.224     brouard  2336: #endif
                   2337: #ifdef LINMINORIGINAL
1.234     brouard  2338:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2339: #else
1.234     brouard  2340:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2341:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2342: #endif
1.234     brouard  2343:        
1.191     brouard  2344: #ifdef DEBUGLINMIN
1.234     brouard  2345:        for (j=1;j<=n;j++) { 
                   2346:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2347:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2348:          if(j % ncovmodel == 0){
                   2349:            printf("\n");
                   2350:            fprintf(ficlog,"\n");
                   2351:          }
                   2352:        }
1.224     brouard  2353: #endif
1.234     brouard  2354:        for (j=1;j<=n;j++) { 
                   2355:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2356:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2357:        }
1.224     brouard  2358: #ifdef LINMINORIGINAL
                   2359: #else
1.234     brouard  2360:        for (j=1, flatd=0;j<=n;j++) {
                   2361:          if(flatdir[j]>0)
                   2362:            flatd++;
                   2363:        }
                   2364:        if(flatd >0){
                   2365:          printf("%d flat directions\n",flatd);
                   2366:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2367:          for (j=1;j<=n;j++) { 
                   2368:            if(flatdir[j]>0){
                   2369:              printf("%d ",j);
                   2370:              fprintf(ficlog,"%d ",j);
                   2371:            }
                   2372:          }
                   2373:          printf("\n");
                   2374:          fprintf(ficlog,"\n");
                   2375:        }
1.191     brouard  2376: #endif
1.234     brouard  2377:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2378:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2379:        
1.126     brouard  2380: #ifdef DEBUG
1.234     brouard  2381:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2382:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2383:        for(j=1;j<=n;j++){
                   2384:          printf(" %lf",xit[j]);
                   2385:          fprintf(ficlog," %lf",xit[j]);
                   2386:        }
                   2387:        printf("\n");
                   2388:        fprintf(ficlog,"\n");
1.126     brouard  2389: #endif
1.192     brouard  2390:       } /* end of t or directest negative */
1.224     brouard  2391: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2392: #else
1.234     brouard  2393:       } /* end if (fptt < fp)  */
1.192     brouard  2394: #endif
1.225     brouard  2395: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2396:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2397: #else
1.224     brouard  2398: #endif
1.234     brouard  2399:                } /* loop iteration */ 
1.126     brouard  2400: } 
1.234     brouard  2401:   
1.126     brouard  2402: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2403:   
1.235     brouard  2404:   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  2405:   {
1.235     brouard  2406:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2407:        (and selected quantitative values in nres)
                   2408:        by left multiplying the unit
1.234     brouard  2409:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2410:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2411:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2412:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2413:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2414:   /* Initial matrix pimij */
                   2415:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2416:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2417:   /*  0,                   0                  , 1} */
                   2418:   /*
                   2419:    * and after some iteration: */
                   2420:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2421:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2422:   /*  0,                   0                  , 1} */
                   2423:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2424:   /* {0.51571254859325999, 0.4842874514067399, */
                   2425:   /*  0.51326036147820708, 0.48673963852179264} */
                   2426:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2427:     
1.126     brouard  2428:   int i, ii,j,k;
1.209     brouard  2429:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2430:   /* double **matprod2(); */ /* test */
1.218     brouard  2431:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2432:   double **newm;
1.209     brouard  2433:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2434:   int ncvloop=0;
1.169     brouard  2435:   
1.209     brouard  2436:   min=vector(1,nlstate);
                   2437:   max=vector(1,nlstate);
                   2438:   meandiff=vector(1,nlstate);
                   2439: 
1.218     brouard  2440:        /* Starting with matrix unity */
1.126     brouard  2441:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2442:     for (j=1;j<=nlstate+ndeath;j++){
                   2443:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2444:     }
1.169     brouard  2445:   
                   2446:   cov[1]=1.;
                   2447:   
                   2448:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2449:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2450:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2451:     ncvloop++;
1.126     brouard  2452:     newm=savm;
                   2453:     /* Covariates have to be included here again */
1.138     brouard  2454:     cov[2]=agefin;
1.187     brouard  2455:     if(nagesqr==1)
                   2456:       cov[3]= agefin*agefin;;
1.234     brouard  2457:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2458:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2459:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2460:       /* 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  2461:     }
                   2462:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2463:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2464:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2465:       /* 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  2466:     }
1.237     brouard  2467:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2468:       if(Dummy[Tvar[Tage[k]]]){
                   2469:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2470:       } else{
1.235     brouard  2471:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2472:       }
1.235     brouard  2473:       /* 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  2474:     }
1.237     brouard  2475:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2476:       /* 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  2477:       if(Dummy[Tvard[k][1]==0]){
                   2478:        if(Dummy[Tvard[k][2]==0]){
                   2479:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2480:        }else{
                   2481:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2482:        }
                   2483:       }else{
                   2484:        if(Dummy[Tvard[k][2]==0]){
                   2485:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2486:        }else{
                   2487:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2488:        }
                   2489:       }
1.234     brouard  2490:     }
1.138     brouard  2491:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2492:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2493:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2494:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2495:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2496:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2497:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2498:     
1.126     brouard  2499:     savm=oldm;
                   2500:     oldm=newm;
1.209     brouard  2501: 
                   2502:     for(j=1; j<=nlstate; j++){
                   2503:       max[j]=0.;
                   2504:       min[j]=1.;
                   2505:     }
                   2506:     for(i=1;i<=nlstate;i++){
                   2507:       sumnew=0;
                   2508:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2509:       for(j=1; j<=nlstate; j++){ 
                   2510:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2511:        max[j]=FMAX(max[j],prlim[i][j]);
                   2512:        min[j]=FMIN(min[j],prlim[i][j]);
                   2513:       }
                   2514:     }
                   2515: 
1.126     brouard  2516:     maxmax=0.;
1.209     brouard  2517:     for(j=1; j<=nlstate; j++){
                   2518:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2519:       maxmax=FMAX(maxmax,meandiff[j]);
                   2520:       /* 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  2521:     } /* j loop */
1.203     brouard  2522:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2523:     /* 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  2524:     if(maxmax < ftolpl){
1.209     brouard  2525:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2526:       free_vector(min,1,nlstate);
                   2527:       free_vector(max,1,nlstate);
                   2528:       free_vector(meandiff,1,nlstate);
1.126     brouard  2529:       return prlim;
                   2530:     }
1.169     brouard  2531:   } /* age loop */
1.208     brouard  2532:     /* After some age loop it doesn't converge */
1.209     brouard  2533:   printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
1.208     brouard  2534: Earliest 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);
1.209     brouard  2535:   /* 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); */
                   2536:   free_vector(min,1,nlstate);
                   2537:   free_vector(max,1,nlstate);
                   2538:   free_vector(meandiff,1,nlstate);
1.208     brouard  2539:   
1.169     brouard  2540:   return prlim; /* should not reach here */
1.126     brouard  2541: }
                   2542: 
1.217     brouard  2543: 
                   2544:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2545: 
1.218     brouard  2546:  /* 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) */
                   2547:  /* 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  2548:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2549: {
1.218     brouard  2550:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2551:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2552:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2553:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2554:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2555:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2556:   /* Initial matrix pimij */
                   2557:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2558:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2559:   /*  0,                   0                  , 1} */
                   2560:   /*
                   2561:    * and after some iteration: */
                   2562:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2563:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2564:   /*  0,                   0                  , 1} */
                   2565:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2566:   /* {0.51571254859325999, 0.4842874514067399, */
                   2567:   /*  0.51326036147820708, 0.48673963852179264} */
                   2568:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2569: 
                   2570:   int i, ii,j,k;
                   2571:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2572:   /* double **matprod2(); */ /* test */
                   2573:   double **out, cov[NCOVMAX+1], **bmij();
                   2574:   double **newm;
1.218     brouard  2575:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2576:   double        **oldm, **savm;  /* for use */
                   2577: 
1.217     brouard  2578:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2579:   int ncvloop=0;
                   2580:   
                   2581:   min=vector(1,nlstate);
                   2582:   max=vector(1,nlstate);
                   2583:   meandiff=vector(1,nlstate);
                   2584: 
1.218     brouard  2585:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2586:        oldm=oldms; savm=savms;
                   2587: 
                   2588:        /* Starting with matrix unity */
                   2589:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2590:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2591:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2592:     }
                   2593:   
                   2594:   cov[1]=1.;
                   2595:   
                   2596:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2597:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2598:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2599:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2600:     ncvloop++;
1.218     brouard  2601:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2602:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2603:     /* Covariates have to be included here again */
                   2604:     cov[2]=agefin;
                   2605:     if(nagesqr==1)
                   2606:       cov[3]= agefin*agefin;;
1.242   ! brouard  2607:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
        !          2608:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
        !          2609:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
        !          2610:       /* printf("bprevalim 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)); */
        !          2611:     }
        !          2612:     /* for (k=1; k<=cptcovn;k++) { */
        !          2613:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
        !          2614:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
        !          2615:     /*   /\* 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])]); *\/ */
        !          2616:     /* } */
        !          2617:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
        !          2618:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
        !          2619:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
        !          2620:       /* 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]); */
        !          2621:     }
        !          2622:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
        !          2623:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
        !          2624:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
        !          2625:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
        !          2626:     for (k=1; k<=cptcovage;k++){  /* For product with age */
        !          2627:       if(Dummy[Tvar[Tage[k]]]){
        !          2628:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
        !          2629:       } else{
        !          2630:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
        !          2631:       }
        !          2632:       /* 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]); */
        !          2633:     }
        !          2634:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
        !          2635:       /* 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]); */
        !          2636:       if(Dummy[Tvard[k][1]==0]){
        !          2637:        if(Dummy[Tvard[k][2]==0]){
        !          2638:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
        !          2639:        }else{
        !          2640:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
        !          2641:        }
        !          2642:       }else{
        !          2643:        if(Dummy[Tvard[k][2]==0]){
        !          2644:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
        !          2645:        }else{
        !          2646:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
        !          2647:        }
        !          2648:       }
1.217     brouard  2649:     }
                   2650:     
                   2651:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2652:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2653:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2654:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2655:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2656:                /* ij should be linked to the correct index of cov */
                   2657:                /* age and covariate values ij are in 'cov', but we need to pass
                   2658:                 * ij for the observed prevalence at age and status and covariate
                   2659:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2660:                 */
                   2661:     /* 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 *\/ */
                   2662:     /* 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 *\/ */
                   2663:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
1.217     brouard  2664:     savm=oldm;
                   2665:     oldm=newm;
                   2666:     for(j=1; j<=nlstate; j++){
                   2667:       max[j]=0.;
                   2668:       min[j]=1.;
                   2669:     }
                   2670:     for(j=1; j<=nlstate; j++){ 
                   2671:       for(i=1;i<=nlstate;i++){
1.234     brouard  2672:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2673:        bprlim[i][j]= newm[i][j];
                   2674:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2675:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2676:       }
                   2677:     }
1.218     brouard  2678:                
1.217     brouard  2679:     maxmax=0.;
                   2680:     for(i=1; i<=nlstate; i++){
                   2681:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2682:       maxmax=FMAX(maxmax,meandiff[i]);
                   2683:       /* 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); */
                   2684:     } /* j loop */
                   2685:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2686:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2687:     if(maxmax < ftolpl){
1.220     brouard  2688:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2689:       free_vector(min,1,nlstate);
                   2690:       free_vector(max,1,nlstate);
                   2691:       free_vector(meandiff,1,nlstate);
                   2692:       return bprlim;
                   2693:     }
                   2694:   } /* age loop */
                   2695:     /* After some age loop it doesn't converge */
                   2696:   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'. \n\
                   2697: 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);
                   2698:   /* 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); */
                   2699:   free_vector(min,1,nlstate);
                   2700:   free_vector(max,1,nlstate);
                   2701:   free_vector(meandiff,1,nlstate);
                   2702:   
                   2703:   return bprlim; /* should not reach here */
                   2704: }
                   2705: 
1.126     brouard  2706: /*************** transition probabilities ***************/ 
                   2707: 
                   2708: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2709: {
1.138     brouard  2710:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2711:      computes the probability to be observed in state j being in state i by appying the
                   2712:      model to the ncovmodel covariates (including constant and age).
                   2713:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2714:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2715:      ncth covariate in the global vector x is given by the formula:
                   2716:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2717:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2718:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2719:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2720:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2721:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2722:   */
                   2723:   double s1, lnpijopii;
1.126     brouard  2724:   /*double t34;*/
1.164     brouard  2725:   int i,j, nc, ii, jj;
1.126     brouard  2726: 
1.223     brouard  2727:   for(i=1; i<= nlstate; i++){
                   2728:     for(j=1; j<i;j++){
                   2729:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2730:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2731:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2732:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2733:       }
                   2734:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2735:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2736:     }
                   2737:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2738:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2739:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2740:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2741:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2742:       }
                   2743:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2744:     }
                   2745:   }
1.218     brouard  2746:   
1.223     brouard  2747:   for(i=1; i<= nlstate; i++){
                   2748:     s1=0;
                   2749:     for(j=1; j<i; j++){
                   2750:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2751:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2752:     }
                   2753:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2754:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2755:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2756:     }
                   2757:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2758:     ps[i][i]=1./(s1+1.);
                   2759:     /* Computing other pijs */
                   2760:     for(j=1; j<i; j++)
                   2761:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2762:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2763:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2764:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2765:   } /* end i */
1.218     brouard  2766:   
1.223     brouard  2767:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2768:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2769:       ps[ii][jj]=0;
                   2770:       ps[ii][ii]=1;
                   2771:     }
                   2772:   }
1.218     brouard  2773:   
                   2774:   
1.223     brouard  2775:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2776:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2777:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2778:   /*   } */
                   2779:   /*   printf("\n "); */
                   2780:   /* } */
                   2781:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2782:   /*
                   2783:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2784:                goto end;*/
1.223     brouard  2785:   return ps;
1.126     brouard  2786: }
                   2787: 
1.218     brouard  2788: /*************** backward transition probabilities ***************/ 
                   2789: 
                   2790:  /* 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 ) */
                   2791: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2792:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2793: {
1.222     brouard  2794:   /* Computes the backward probability at age agefin and covariate ij
                   2795:    * and returns in **ps as well as **bmij.
                   2796:    */
1.218     brouard  2797:   int i, ii, j,k;
1.222     brouard  2798:   
                   2799:   double **out, **pmij();
                   2800:   double sumnew=0.;
1.218     brouard  2801:   double agefin;
1.222     brouard  2802:   
                   2803:   double **dnewm, **dsavm, **doldm;
                   2804:   double **bbmij;
                   2805:   
1.218     brouard  2806:   doldm=ddoldms; /* global pointers */
1.222     brouard  2807:   dnewm=ddnewms;
                   2808:   dsavm=ddsavms;
                   2809:   
                   2810:   agefin=cov[2];
                   2811:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2812:      the observed prevalence (with this covariate ij) */
                   2813:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2814:   /* We do have the matrix Px in savm  and we need pij */
                   2815:   for (j=1;j<=nlstate+ndeath;j++){
                   2816:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2817:     for (ii=1;ii<=nlstate;ii++){
                   2818:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2819:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2820:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2821:       if(sumnew >= 1.e-10){
                   2822:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2823:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2824:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2825:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2826:        /* }else */
                   2827:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2828:       }else{
1.242   ! brouard  2829:        ;
        !          2830:        /* printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin); */
1.222     brouard  2831:       }
                   2832:     } /*End ii */
                   2833:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2834:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2835:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2836:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2837:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2838:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2839:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2840:   for (j=1;j<=nlstate+ndeath;j++){
                   2841:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2842:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2843:     }
                   2844:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2845:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2846:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2847:   /* end bmij */
                   2848:   return ps; 
1.218     brouard  2849: }
1.217     brouard  2850: /*************** transition probabilities ***************/ 
                   2851: 
1.218     brouard  2852: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2853: {
                   2854:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2855:      computes the probability to be observed in state j being in state i by appying the
                   2856:      model to the ncovmodel covariates (including constant and age).
                   2857:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2858:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2859:      ncth covariate in the global vector x is given by the formula:
                   2860:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2861:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2862:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2863:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2864:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2865:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2866:   */
                   2867:   double s1, lnpijopii;
                   2868:   /*double t34;*/
                   2869:   int i,j, nc, ii, jj;
                   2870: 
1.234     brouard  2871:   for(i=1; i<= nlstate; i++){
                   2872:     for(j=1; j<i;j++){
                   2873:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2874:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2875:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2876:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2877:       }
                   2878:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2879:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2880:     }
                   2881:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2882:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2883:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2884:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2885:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2886:       }
                   2887:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2888:     }
                   2889:   }
                   2890:   
                   2891:   for(i=1; i<= nlstate; i++){
                   2892:     s1=0;
                   2893:     for(j=1; j<i; j++){
                   2894:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2895:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2896:     }
                   2897:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2898:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2899:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2900:     }
                   2901:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2902:     ps[i][i]=1./(s1+1.);
                   2903:     /* Computing other pijs */
                   2904:     for(j=1; j<i; j++)
                   2905:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2906:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2907:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2908:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2909:   } /* end i */
                   2910:   
                   2911:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2912:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2913:       ps[ii][jj]=0;
                   2914:       ps[ii][ii]=1;
                   2915:     }
                   2916:   }
                   2917:   /* Added for backcast */ /* Transposed matrix too */
                   2918:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2919:     s1=0.;
                   2920:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2921:       s1+=ps[ii][jj];
                   2922:     }
                   2923:     for(ii=1; ii<= nlstate; ii++){
                   2924:       ps[ii][jj]=ps[ii][jj]/s1;
                   2925:     }
                   2926:   }
                   2927:   /* Transposition */
                   2928:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2929:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2930:       s1=ps[ii][jj];
                   2931:       ps[ii][jj]=ps[jj][ii];
                   2932:       ps[jj][ii]=s1;
                   2933:     }
                   2934:   }
                   2935:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2936:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2937:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2938:   /*   } */
                   2939:   /*   printf("\n "); */
                   2940:   /* } */
                   2941:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2942:   /*
                   2943:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2944:     goto end;*/
                   2945:   return ps;
1.217     brouard  2946: }
                   2947: 
                   2948: 
1.126     brouard  2949: /**************** Product of 2 matrices ******************/
                   2950: 
1.145     brouard  2951: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2952: {
                   2953:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2954:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2955:   /* in, b, out are matrice of pointers which should have been initialized 
                   2956:      before: only the contents of out is modified. The function returns
                   2957:      a pointer to pointers identical to out */
1.145     brouard  2958:   int i, j, k;
1.126     brouard  2959:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2960:     for(k=ncolol; k<=ncoloh; k++){
                   2961:       out[i][k]=0.;
                   2962:       for(j=ncl; j<=nch; j++)
                   2963:        out[i][k] +=in[i][j]*b[j][k];
                   2964:     }
1.126     brouard  2965:   return out;
                   2966: }
                   2967: 
                   2968: 
                   2969: /************* Higher Matrix Product ***************/
                   2970: 
1.235     brouard  2971: 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  2972: {
1.218     brouard  2973:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2974:      'nhstepm*hstepm*stepm' months (i.e. until
                   2975:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2976:      nhstepm*hstepm matrices. 
                   2977:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2978:      (typically every 2 years instead of every month which is too big 
                   2979:      for the memory).
                   2980:      Model is determined by parameters x and covariates have to be 
                   2981:      included manually here. 
                   2982: 
                   2983:      */
                   2984: 
                   2985:   int i, j, d, h, k;
1.131     brouard  2986:   double **out, cov[NCOVMAX+1];
1.126     brouard  2987:   double **newm;
1.187     brouard  2988:   double agexact;
1.214     brouard  2989:   double agebegin, ageend;
1.126     brouard  2990: 
                   2991:   /* Hstepm could be zero and should return the unit matrix */
                   2992:   for (i=1;i<=nlstate+ndeath;i++)
                   2993:     for (j=1;j<=nlstate+ndeath;j++){
                   2994:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2995:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2996:     }
                   2997:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2998:   for(h=1; h <=nhstepm; h++){
                   2999:     for(d=1; d <=hstepm; d++){
                   3000:       newm=savm;
                   3001:       /* Covariates have to be included here again */
                   3002:       cov[1]=1.;
1.214     brouard  3003:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3004:       cov[2]=agexact;
                   3005:       if(nagesqr==1)
1.227     brouard  3006:        cov[3]= agexact*agexact;
1.235     brouard  3007:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3008:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3009:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3010:        /* 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)); */
                   3011:       }
                   3012:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3013:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3014:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3015:        /* 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]); */
                   3016:       }
                   3017:       for (k=1; k<=cptcovage;k++){
                   3018:        if(Dummy[Tvar[Tage[k]]]){
                   3019:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3020:        } else{
                   3021:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3022:        }
                   3023:        /* 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]); */
                   3024:       }
                   3025:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3026:        /* 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]); */
                   3027:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3028:       }
                   3029:       /* for (k=1; k<=cptcovn;k++)  */
                   3030:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3031:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3032:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3033:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3034:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3035:       
                   3036:       
1.126     brouard  3037:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3038:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3039:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3040:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3041:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3042:       /* if((int)age == 70){ */
                   3043:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3044:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3045:       /*         printf("%d pmmij ",i); */
                   3046:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3047:       /*           printf("%f ",pmmij[i][j]); */
                   3048:       /*         } */
                   3049:       /*         printf(" oldm "); */
                   3050:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3051:       /*           printf("%f ",oldm[i][j]); */
                   3052:       /*         } */
                   3053:       /*         printf("\n"); */
                   3054:       /*       } */
                   3055:       /* } */
1.126     brouard  3056:       savm=oldm;
                   3057:       oldm=newm;
                   3058:     }
                   3059:     for(i=1; i<=nlstate+ndeath; i++)
                   3060:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3061:                                po[i][j][h]=newm[i][j];
                   3062:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3063:       }
1.128     brouard  3064:     /*printf("h=%d ",h);*/
1.126     brouard  3065:   } /* end h */
1.218     brouard  3066:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3067:   return po;
                   3068: }
                   3069: 
1.217     brouard  3070: /************* Higher Back Matrix Product ***************/
1.218     brouard  3071: /* 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.222     brouard  3072: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3073: {
1.218     brouard  3074:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3075:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3076:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3077:      nhstepm*hstepm matrices.
                   3078:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3079:      (typically every 2 years instead of every month which is too big
1.217     brouard  3080:      for the memory).
1.218     brouard  3081:      Model is determined by parameters x and covariates have to be
                   3082:      included manually here.
1.217     brouard  3083: 
1.222     brouard  3084:   */
1.217     brouard  3085: 
                   3086:   int i, j, d, h, k;
                   3087:   double **out, cov[NCOVMAX+1];
                   3088:   double **newm;
                   3089:   double agexact;
                   3090:   double agebegin, ageend;
1.222     brouard  3091:   double **oldm, **savm;
1.217     brouard  3092: 
1.222     brouard  3093:   oldm=oldms;savm=savms;
1.217     brouard  3094:   /* Hstepm could be zero and should return the unit matrix */
                   3095:   for (i=1;i<=nlstate+ndeath;i++)
                   3096:     for (j=1;j<=nlstate+ndeath;j++){
                   3097:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3098:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3099:     }
                   3100:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3101:   for(h=1; h <=nhstepm; h++){
                   3102:     for(d=1; d <=hstepm; d++){
                   3103:       newm=savm;
                   3104:       /* Covariates have to be included here again */
                   3105:       cov[1]=1.;
                   3106:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3107:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3108:       cov[2]=agexact;
                   3109:       if(nagesqr==1)
1.222     brouard  3110:        cov[3]= agexact*agexact;
1.218     brouard  3111:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3112:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3113:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3114:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3115:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3116:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3117:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3118:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3119:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3120:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.218     brouard  3121:                        
                   3122:                        
1.217     brouard  3123:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3124:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3125:       /* Careful transposed matrix */
1.222     brouard  3126:       /* age is in cov[2] */
1.218     brouard  3127:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3128:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3129:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3130:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3131:       /* if((int)age == 70){ */
                   3132:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3133:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3134:       /*         printf("%d pmmij ",i); */
                   3135:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3136:       /*           printf("%f ",pmmij[i][j]); */
                   3137:       /*         } */
                   3138:       /*         printf(" oldm "); */
                   3139:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3140:       /*           printf("%f ",oldm[i][j]); */
                   3141:       /*         } */
                   3142:       /*         printf("\n"); */
                   3143:       /*       } */
                   3144:       /* } */
                   3145:       savm=oldm;
                   3146:       oldm=newm;
                   3147:     }
                   3148:     for(i=1; i<=nlstate+ndeath; i++)
                   3149:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3150:        po[i][j][h]=newm[i][j];
                   3151:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3152:       }
                   3153:     /*printf("h=%d ",h);*/
                   3154:   } /* end h */
1.222     brouard  3155:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3156:   return po;
                   3157: }
                   3158: 
                   3159: 
1.162     brouard  3160: #ifdef NLOPT
                   3161:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3162:   double fret;
                   3163:   double *xt;
                   3164:   int j;
                   3165:   myfunc_data *d2 = (myfunc_data *) pd;
                   3166: /* xt = (p1-1); */
                   3167:   xt=vector(1,n); 
                   3168:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3169: 
                   3170:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3171:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3172:   printf("Function = %.12lf ",fret);
                   3173:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3174:   printf("\n");
                   3175:  free_vector(xt,1,n);
                   3176:   return fret;
                   3177: }
                   3178: #endif
1.126     brouard  3179: 
                   3180: /*************** log-likelihood *************/
                   3181: double func( double *x)
                   3182: {
1.226     brouard  3183:   int i, ii, j, k, mi, d, kk;
                   3184:   int ioffset=0;
                   3185:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3186:   double **out;
                   3187:   double lli; /* Individual log likelihood */
                   3188:   int s1, s2;
1.228     brouard  3189:   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  3190:   double bbh, survp;
                   3191:   long ipmx;
                   3192:   double agexact;
                   3193:   /*extern weight */
                   3194:   /* We are differentiating ll according to initial status */
                   3195:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3196:   /*for(i=1;i<imx;i++) 
                   3197:     printf(" %d\n",s[4][i]);
                   3198:   */
1.162     brouard  3199: 
1.226     brouard  3200:   ++countcallfunc;
1.162     brouard  3201: 
1.226     brouard  3202:   cov[1]=1.;
1.126     brouard  3203: 
1.226     brouard  3204:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3205:   ioffset=0;
1.226     brouard  3206:   if(mle==1){
                   3207:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3208:       /* Computes the values of the ncovmodel covariates of the model
                   3209:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3210:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3211:         to be observed in j being in i according to the model.
                   3212:       */
                   3213:       ioffset=2+nagesqr+cptcovage;
1.233     brouard  3214:    /* Fixed */
1.234     brouard  3215:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3216:        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)*/
                   3217:       }
1.226     brouard  3218:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3219:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3220:         has been calculated etc */
                   3221:       /* For an individual i, wav[i] gives the number of effective waves */
                   3222:       /* We compute the contribution to Likelihood of each effective transition
                   3223:         mw[mi][i] is real wave of the mi th effectve wave */
                   3224:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3225:         s2=s[mw[mi+1][i]][i];
                   3226:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3227:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3228:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3229:       */
                   3230:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3231:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242   ! brouard  3232:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
        !          3233:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3234:        }
                   3235:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3236:          for (j=1;j<=nlstate+ndeath;j++){
                   3237:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3238:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3239:          }
                   3240:        for(d=0; d<dh[mi][i]; d++){
                   3241:          newm=savm;
                   3242:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3243:          cov[2]=agexact;
                   3244:          if(nagesqr==1)
                   3245:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3246:          for (kk=1; kk<=cptcovage;kk++) {
1.242   ! brouard  3247:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3248:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242   ! brouard  3249:          else
        !          3250:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3251:          }
                   3252:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3253:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3254:          savm=oldm;
                   3255:          oldm=newm;
                   3256:        } /* end mult */
                   3257:        
                   3258:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3259:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3260:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3261:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3262:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3263:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3264:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3265:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3266:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3267:                                 * -stepm/2 to stepm/2 .
                   3268:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3269:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3270:                                 */
1.234     brouard  3271:        s1=s[mw[mi][i]][i];
                   3272:        s2=s[mw[mi+1][i]][i];
                   3273:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3274:        /* bias bh is positive if real duration
                   3275:         * is higher than the multiple of stepm and negative otherwise.
                   3276:         */
                   3277:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3278:        if( s2 > nlstate){ 
                   3279:          /* i.e. if s2 is a death state and if the date of death is known 
                   3280:             then the contribution to the likelihood is the probability to 
                   3281:             die between last step unit time and current  step unit time, 
                   3282:             which is also equal to probability to die before dh 
                   3283:             minus probability to die before dh-stepm . 
                   3284:             In version up to 0.92 likelihood was computed
                   3285:             as if date of death was unknown. Death was treated as any other
                   3286:             health state: the date of the interview describes the actual state
                   3287:             and not the date of a change in health state. The former idea was
                   3288:             to consider that at each interview the state was recorded
                   3289:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3290:             introduced the exact date of death then we should have modified
                   3291:             the contribution of an exact death to the likelihood. This new
                   3292:             contribution is smaller and very dependent of the step unit
                   3293:             stepm. It is no more the probability to die between last interview
                   3294:             and month of death but the probability to survive from last
                   3295:             interview up to one month before death multiplied by the
                   3296:             probability to die within a month. Thanks to Chris
                   3297:             Jackson for correcting this bug.  Former versions increased
                   3298:             mortality artificially. The bad side is that we add another loop
                   3299:             which slows down the processing. The difference can be up to 10%
                   3300:             lower mortality.
                   3301:          */
                   3302:          /* If, at the beginning of the maximization mostly, the
                   3303:             cumulative probability or probability to be dead is
                   3304:             constant (ie = 1) over time d, the difference is equal to
                   3305:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3306:             s1 at precedent wave, to be dead a month before current
                   3307:             wave is equal to probability, being at state s1 at
                   3308:             precedent wave, to be dead at mont of the current
                   3309:             wave. Then the observed probability (that this person died)
                   3310:             is null according to current estimated parameter. In fact,
                   3311:             it should be very low but not zero otherwise the log go to
                   3312:             infinity.
                   3313:          */
1.183     brouard  3314: /* #ifdef INFINITYORIGINAL */
                   3315: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3316: /* #else */
                   3317: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3318: /*         lli=log(mytinydouble); */
                   3319: /*       else */
                   3320: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3321: /* #endif */
1.226     brouard  3322:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3323:          
1.226     brouard  3324:        } else if  ( s2==-1 ) { /* alive */
                   3325:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3326:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3327:          /*survp += out[s1][j]; */
                   3328:          lli= log(survp);
                   3329:        }
                   3330:        else if  (s2==-4) { 
                   3331:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3332:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3333:          lli= log(survp); 
                   3334:        } 
                   3335:        else if  (s2==-5) { 
                   3336:          for (j=1,survp=0. ; j<=2; j++)  
                   3337:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3338:          lli= log(survp); 
                   3339:        } 
                   3340:        else{
                   3341:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3342:          /*  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 */
                   3343:        } 
                   3344:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3345:        /*if(lli ==000.0)*/
                   3346:        /*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); */
                   3347:        ipmx +=1;
                   3348:        sw += weight[i];
                   3349:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3350:        /* if (lli < log(mytinydouble)){ */
                   3351:        /*   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); */
                   3352:        /*   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]); */
                   3353:        /* } */
                   3354:       } /* end of wave */
                   3355:     } /* end of individual */
                   3356:   }  else if(mle==2){
                   3357:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3358:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3359:       for(mi=1; mi<= wav[i]-1; mi++){
                   3360:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3361:          for (j=1;j<=nlstate+ndeath;j++){
                   3362:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3363:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3364:          }
                   3365:        for(d=0; d<=dh[mi][i]; d++){
                   3366:          newm=savm;
                   3367:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3368:          cov[2]=agexact;
                   3369:          if(nagesqr==1)
                   3370:            cov[3]= agexact*agexact;
                   3371:          for (kk=1; kk<=cptcovage;kk++) {
                   3372:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3373:          }
                   3374:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3375:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3376:          savm=oldm;
                   3377:          oldm=newm;
                   3378:        } /* end mult */
                   3379:       
                   3380:        s1=s[mw[mi][i]][i];
                   3381:        s2=s[mw[mi+1][i]][i];
                   3382:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3383:        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 */
                   3384:        ipmx +=1;
                   3385:        sw += weight[i];
                   3386:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3387:       } /* end of wave */
                   3388:     } /* end of individual */
                   3389:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3390:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3391:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3392:       for(mi=1; mi<= wav[i]-1; mi++){
                   3393:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3394:          for (j=1;j<=nlstate+ndeath;j++){
                   3395:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3396:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3397:          }
                   3398:        for(d=0; d<dh[mi][i]; d++){
                   3399:          newm=savm;
                   3400:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3401:          cov[2]=agexact;
                   3402:          if(nagesqr==1)
                   3403:            cov[3]= agexact*agexact;
                   3404:          for (kk=1; kk<=cptcovage;kk++) {
                   3405:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3406:          }
                   3407:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3408:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3409:          savm=oldm;
                   3410:          oldm=newm;
                   3411:        } /* end mult */
                   3412:       
                   3413:        s1=s[mw[mi][i]][i];
                   3414:        s2=s[mw[mi+1][i]][i];
                   3415:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3416:        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 */
                   3417:        ipmx +=1;
                   3418:        sw += weight[i];
                   3419:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3420:       } /* end of wave */
                   3421:     } /* end of individual */
                   3422:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3423:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3424:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3425:       for(mi=1; mi<= wav[i]-1; mi++){
                   3426:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3427:          for (j=1;j<=nlstate+ndeath;j++){
                   3428:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3429:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3430:          }
                   3431:        for(d=0; d<dh[mi][i]; d++){
                   3432:          newm=savm;
                   3433:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3434:          cov[2]=agexact;
                   3435:          if(nagesqr==1)
                   3436:            cov[3]= agexact*agexact;
                   3437:          for (kk=1; kk<=cptcovage;kk++) {
                   3438:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3439:          }
1.126     brouard  3440:        
1.226     brouard  3441:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3442:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3443:          savm=oldm;
                   3444:          oldm=newm;
                   3445:        } /* end mult */
                   3446:       
                   3447:        s1=s[mw[mi][i]][i];
                   3448:        s2=s[mw[mi+1][i]][i];
                   3449:        if( s2 > nlstate){ 
                   3450:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3451:        } else if  ( s2==-1 ) { /* alive */
                   3452:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3453:            survp += out[s1][j];
                   3454:          lli= log(survp);
                   3455:        }else{
                   3456:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3457:        }
                   3458:        ipmx +=1;
                   3459:        sw += weight[i];
                   3460:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3461: /*     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  3462:       } /* end of wave */
                   3463:     } /* end of individual */
                   3464:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3465:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3466:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3467:       for(mi=1; mi<= wav[i]-1; mi++){
                   3468:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3469:          for (j=1;j<=nlstate+ndeath;j++){
                   3470:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3471:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3472:          }
                   3473:        for(d=0; d<dh[mi][i]; d++){
                   3474:          newm=savm;
                   3475:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3476:          cov[2]=agexact;
                   3477:          if(nagesqr==1)
                   3478:            cov[3]= agexact*agexact;
                   3479:          for (kk=1; kk<=cptcovage;kk++) {
                   3480:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3481:          }
1.126     brouard  3482:        
1.226     brouard  3483:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3484:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3485:          savm=oldm;
                   3486:          oldm=newm;
                   3487:        } /* end mult */
                   3488:       
                   3489:        s1=s[mw[mi][i]][i];
                   3490:        s2=s[mw[mi+1][i]][i];
                   3491:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3492:        ipmx +=1;
                   3493:        sw += weight[i];
                   3494:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3495:        /*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]);*/
                   3496:       } /* end of wave */
                   3497:     } /* end of individual */
                   3498:   } /* End of if */
                   3499:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3500:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3501:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3502:   return -l;
1.126     brouard  3503: }
                   3504: 
                   3505: /*************** log-likelihood *************/
                   3506: double funcone( double *x)
                   3507: {
1.228     brouard  3508:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3509:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3510:   int ioffset=0;
1.131     brouard  3511:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3512:   double **out;
                   3513:   double lli; /* Individual log likelihood */
                   3514:   double llt;
                   3515:   int s1, s2;
1.228     brouard  3516:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3517: 
1.126     brouard  3518:   double bbh, survp;
1.187     brouard  3519:   double agexact;
1.214     brouard  3520:   double agebegin, ageend;
1.126     brouard  3521:   /*extern weight */
                   3522:   /* We are differentiating ll according to initial status */
                   3523:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3524:   /*for(i=1;i<imx;i++) 
                   3525:     printf(" %d\n",s[4][i]);
                   3526:   */
                   3527:   cov[1]=1.;
                   3528: 
                   3529:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3530:   ioffset=0;
                   3531:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.225     brouard  3532:     ioffset=2+nagesqr+cptcovage;
1.232     brouard  3533:     /* Fixed */
1.224     brouard  3534:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3535:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3536:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3537:       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)*/
                   3538: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3539: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3540: /*    cov[2+6]=covar[2][i]; V2  */
                   3541: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3542: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3543: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3544: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3545: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3546: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3547:     }
1.232     brouard  3548:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3549:     /*   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?)*\/ */
                   3550:     /* } */
1.231     brouard  3551:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3552:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3553:     /* } */
1.225     brouard  3554:     
1.233     brouard  3555: 
                   3556:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3557:     /* Wave varying (but not age varying) */
                   3558:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242   ! brouard  3559:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
        !          3560:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
        !          3561:       }
1.232     brouard  3562:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242   ! brouard  3563:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
        !          3564:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
        !          3565:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
        !          3566:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
        !          3567:       /* 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  3568:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242   ! brouard  3569:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
        !          3570:       /*       /\* 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]); *\/ */
        !          3571:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3572:       /* } */
1.126     brouard  3573:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242   ! brouard  3574:        for (j=1;j<=nlstate+ndeath;j++){
        !          3575:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3576:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3577:        }
1.214     brouard  3578:       
                   3579:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3580:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3581:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.242   ! brouard  3582:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
        !          3583:          and mw[mi+1][i]. dh depends on stepm.*/
        !          3584:        newm=savm;
        !          3585:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3586:        cov[2]=agexact;
        !          3587:        if(nagesqr==1)
        !          3588:          cov[3]= agexact*agexact;
        !          3589:        for (kk=1; kk<=cptcovage;kk++) {
        !          3590:          if(!FixedV[Tvar[Tage[kk]]])
        !          3591:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3592:          else
        !          3593:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
        !          3594:        }
        !          3595:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
        !          3596:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
        !          3597:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3598:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3599:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
        !          3600:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
        !          3601:        savm=oldm;
        !          3602:        oldm=newm;
1.126     brouard  3603:       } /* end mult */
                   3604:       
                   3605:       s1=s[mw[mi][i]][i];
                   3606:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3607:       /* if(s2==-1){ */
                   3608:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3609:       /*       /\* exit(1); *\/ */
                   3610:       /* } */
1.126     brouard  3611:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3612:       /* bias is positive if real duration
                   3613:        * is higher than the multiple of stepm and negative otherwise.
                   3614:        */
                   3615:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242   ! brouard  3616:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3617:       } else if  ( s2==-1 ) { /* alive */
1.242   ! brouard  3618:        for (j=1,survp=0. ; j<=nlstate; j++) 
        !          3619:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          3620:        lli= log(survp);
1.126     brouard  3621:       }else if (mle==1){
1.242   ! brouard  3622:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3623:       } else if(mle==2){
1.242   ! brouard  3624:        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  3625:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242   ! brouard  3626:        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  3627:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242   ! brouard  3628:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3629:       } else{  /* mle=0 back to 1 */
1.242   ! brouard  3630:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          3631:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3632:       } /* End of if */
                   3633:       ipmx +=1;
                   3634:       sw += weight[i];
                   3635:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3636:       /*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  3637:       if(globpr){
1.242   ! brouard  3638:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3639:  %11.6f %11.6f %11.6f ", \
1.242   ! brouard  3640:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
        !          3641:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
        !          3642:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
        !          3643:          llt +=ll[k]*gipmx/gsw;
        !          3644:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
        !          3645:        }
        !          3646:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3647:       }
1.232     brouard  3648:        } /* end of wave */
                   3649: } /* end of individual */
                   3650: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3651: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3652: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3653: if(globpr==0){ /* First time we count the contributions and weights */
                   3654:        gipmx=ipmx;
                   3655:        gsw=sw;
                   3656: }
                   3657: return -l;
1.126     brouard  3658: }
                   3659: 
                   3660: 
                   3661: /*************** function likelione ***********/
                   3662: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3663: {
                   3664:   /* This routine should help understanding what is done with 
                   3665:      the selection of individuals/waves and
                   3666:      to check the exact contribution to the likelihood.
                   3667:      Plotting could be done.
                   3668:    */
                   3669:   int k;
                   3670: 
                   3671:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3672:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3673:     strcat(fileresilk,fileresu);
1.126     brouard  3674:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3675:       printf("Problem with resultfile: %s\n", fileresilk);
                   3676:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3677:     }
1.214     brouard  3678:     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");
                   3679:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3680:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3681:     for(k=1; k<=nlstate; k++) 
                   3682:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3683:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3684:   }
                   3685: 
                   3686:   *fretone=(*funcone)(p);
                   3687:   if(*globpri !=0){
                   3688:     fclose(ficresilk);
1.205     brouard  3689:     if (mle ==0)
                   3690:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3691:     else if(mle >=1)
                   3692:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3693:     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.207     brouard  3694:     
1.208     brouard  3695:       
                   3696:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3697:       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  3698: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3699:     }
1.207     brouard  3700:     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  3701: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3702:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3703: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3704:     fflush(fichtm);
1.205     brouard  3705:   }
1.126     brouard  3706:   return;
                   3707: }
                   3708: 
                   3709: 
                   3710: /*********** Maximum Likelihood Estimation ***************/
                   3711: 
                   3712: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3713: {
1.165     brouard  3714:   int i,j, iter=0;
1.126     brouard  3715:   double **xi;
                   3716:   double fret;
                   3717:   double fretone; /* Only one call to likelihood */
                   3718:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3719: 
                   3720: #ifdef NLOPT
                   3721:   int creturn;
                   3722:   nlopt_opt opt;
                   3723:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3724:   double *lb;
                   3725:   double minf; /* the minimum objective value, upon return */
                   3726:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3727:   myfunc_data dinst, *d = &dinst;
                   3728: #endif
                   3729: 
                   3730: 
1.126     brouard  3731:   xi=matrix(1,npar,1,npar);
                   3732:   for (i=1;i<=npar;i++)
                   3733:     for (j=1;j<=npar;j++)
                   3734:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3735:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3736:   strcpy(filerespow,"POW_"); 
1.126     brouard  3737:   strcat(filerespow,fileres);
                   3738:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3739:     printf("Problem with resultfile: %s\n", filerespow);
                   3740:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3741:   }
                   3742:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3743:   for (i=1;i<=nlstate;i++)
                   3744:     for(j=1;j<=nlstate+ndeath;j++)
                   3745:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3746:   fprintf(ficrespow,"\n");
1.162     brouard  3747: #ifdef POWELL
1.126     brouard  3748:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3749: #endif
1.126     brouard  3750: 
1.162     brouard  3751: #ifdef NLOPT
                   3752: #ifdef NEWUOA
                   3753:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3754: #else
                   3755:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3756: #endif
                   3757:   lb=vector(0,npar-1);
                   3758:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3759:   nlopt_set_lower_bounds(opt, lb);
                   3760:   nlopt_set_initial_step1(opt, 0.1);
                   3761:   
                   3762:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3763:   d->function = func;
                   3764:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3765:   nlopt_set_min_objective(opt, myfunc, d);
                   3766:   nlopt_set_xtol_rel(opt, ftol);
                   3767:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3768:     printf("nlopt failed! %d\n",creturn); 
                   3769:   }
                   3770:   else {
                   3771:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3772:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3773:     iter=1; /* not equal */
                   3774:   }
                   3775:   nlopt_destroy(opt);
                   3776: #endif
1.126     brouard  3777:   free_matrix(xi,1,npar,1,npar);
                   3778:   fclose(ficrespow);
1.203     brouard  3779:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3780:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3781:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3782: 
                   3783: }
                   3784: 
                   3785: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3786: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3787: {
                   3788:   double  **a,**y,*x,pd;
1.203     brouard  3789:   /* double **hess; */
1.164     brouard  3790:   int i, j;
1.126     brouard  3791:   int *indx;
                   3792: 
                   3793:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3794:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3795:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3796:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3797:   double gompertz(double p[]);
1.203     brouard  3798:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3799: 
                   3800:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3801:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3802:   for (i=1;i<=npar;i++){
1.203     brouard  3803:     printf("%d-",i);fflush(stdout);
                   3804:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3805:    
                   3806:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3807:     
                   3808:     /*  printf(" %f ",p[i]);
                   3809:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3810:   }
                   3811:   
                   3812:   for (i=1;i<=npar;i++) {
                   3813:     for (j=1;j<=npar;j++)  {
                   3814:       if (j>i) { 
1.203     brouard  3815:        printf(".%d-%d",i,j);fflush(stdout);
                   3816:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3817:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3818:        
                   3819:        hess[j][i]=hess[i][j];    
                   3820:        /*printf(" %lf ",hess[i][j]);*/
                   3821:       }
                   3822:     }
                   3823:   }
                   3824:   printf("\n");
                   3825:   fprintf(ficlog,"\n");
                   3826: 
                   3827:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3828:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3829:   
                   3830:   a=matrix(1,npar,1,npar);
                   3831:   y=matrix(1,npar,1,npar);
                   3832:   x=vector(1,npar);
                   3833:   indx=ivector(1,npar);
                   3834:   for (i=1;i<=npar;i++)
                   3835:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3836:   ludcmp(a,npar,indx,&pd);
                   3837: 
                   3838:   for (j=1;j<=npar;j++) {
                   3839:     for (i=1;i<=npar;i++) x[i]=0;
                   3840:     x[j]=1;
                   3841:     lubksb(a,npar,indx,x);
                   3842:     for (i=1;i<=npar;i++){ 
                   3843:       matcov[i][j]=x[i];
                   3844:     }
                   3845:   }
                   3846: 
                   3847:   printf("\n#Hessian matrix#\n");
                   3848:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3849:   for (i=1;i<=npar;i++) { 
                   3850:     for (j=1;j<=npar;j++) { 
1.203     brouard  3851:       printf("%.6e ",hess[i][j]);
                   3852:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3853:     }
                   3854:     printf("\n");
                   3855:     fprintf(ficlog,"\n");
                   3856:   }
                   3857: 
1.203     brouard  3858:   /* printf("\n#Covariance matrix#\n"); */
                   3859:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3860:   /* for (i=1;i<=npar;i++) {  */
                   3861:   /*   for (j=1;j<=npar;j++) {  */
                   3862:   /*     printf("%.6e ",matcov[i][j]); */
                   3863:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3864:   /*   } */
                   3865:   /*   printf("\n"); */
                   3866:   /*   fprintf(ficlog,"\n"); */
                   3867:   /* } */
                   3868: 
1.126     brouard  3869:   /* Recompute Inverse */
1.203     brouard  3870:   /* for (i=1;i<=npar;i++) */
                   3871:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3872:   /* ludcmp(a,npar,indx,&pd); */
                   3873: 
                   3874:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3875: 
                   3876:   /* for (j=1;j<=npar;j++) { */
                   3877:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3878:   /*   x[j]=1; */
                   3879:   /*   lubksb(a,npar,indx,x); */
                   3880:   /*   for (i=1;i<=npar;i++){  */
                   3881:   /*     y[i][j]=x[i]; */
                   3882:   /*     printf("%.3e ",y[i][j]); */
                   3883:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3884:   /*   } */
                   3885:   /*   printf("\n"); */
                   3886:   /*   fprintf(ficlog,"\n"); */
                   3887:   /* } */
                   3888: 
                   3889:   /* Verifying the inverse matrix */
                   3890: #ifdef DEBUGHESS
                   3891:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3892: 
1.203     brouard  3893:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3894:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3895: 
                   3896:   for (j=1;j<=npar;j++) {
                   3897:     for (i=1;i<=npar;i++){ 
1.203     brouard  3898:       printf("%.2f ",y[i][j]);
                   3899:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3900:     }
                   3901:     printf("\n");
                   3902:     fprintf(ficlog,"\n");
                   3903:   }
1.203     brouard  3904: #endif
1.126     brouard  3905: 
                   3906:   free_matrix(a,1,npar,1,npar);
                   3907:   free_matrix(y,1,npar,1,npar);
                   3908:   free_vector(x,1,npar);
                   3909:   free_ivector(indx,1,npar);
1.203     brouard  3910:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3911: 
                   3912: 
                   3913: }
                   3914: 
                   3915: /*************** hessian matrix ****************/
                   3916: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3917: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3918:   int i;
                   3919:   int l=1, lmax=20;
1.203     brouard  3920:   double k1,k2, res, fx;
1.132     brouard  3921:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3922:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3923:   int k=0,kmax=10;
                   3924:   double l1;
                   3925: 
                   3926:   fx=func(x);
                   3927:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3928:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3929:     l1=pow(10,l);
                   3930:     delts=delt;
                   3931:     for(k=1 ; k <kmax; k=k+1){
                   3932:       delt = delta*(l1*k);
                   3933:       p2[theta]=x[theta] +delt;
1.145     brouard  3934:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3935:       p2[theta]=x[theta]-delt;
                   3936:       k2=func(p2)-fx;
                   3937:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3938:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3939:       
1.203     brouard  3940: #ifdef DEBUGHESSII
1.126     brouard  3941:       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);
                   3942:       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);
                   3943: #endif
                   3944:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3945:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3946:        k=kmax;
                   3947:       }
                   3948:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3949:        k=kmax; l=lmax*10;
1.126     brouard  3950:       }
                   3951:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3952:        delts=delt;
                   3953:       }
1.203     brouard  3954:     } /* End loop k */
1.126     brouard  3955:   }
                   3956:   delti[theta]=delts;
                   3957:   return res; 
                   3958:   
                   3959: }
                   3960: 
1.203     brouard  3961: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3962: {
                   3963:   int i;
1.164     brouard  3964:   int l=1, lmax=20;
1.126     brouard  3965:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3966:   double p2[MAXPARM+1];
1.203     brouard  3967:   int k, kmax=1;
                   3968:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3969: 
                   3970:   int firstime=0;
1.203     brouard  3971:   
1.126     brouard  3972:   fx=func(x);
1.203     brouard  3973:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3974:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3975:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3976:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3977:     k1=func(p2)-fx;
                   3978:   
1.203     brouard  3979:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3980:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3981:     k2=func(p2)-fx;
                   3982:   
1.203     brouard  3983:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3984:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3985:     k3=func(p2)-fx;
                   3986:   
1.203     brouard  3987:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3988:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3989:     k4=func(p2)-fx;
1.203     brouard  3990:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3991:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3992:       firstime=1;
1.203     brouard  3993:       kmax=kmax+10;
1.208     brouard  3994:     }
                   3995:     if(kmax >=10 || firstime ==1){
1.218     brouard  3996:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3997:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  3998:       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);
                   3999:       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);
                   4000:     }
                   4001: #ifdef DEBUGHESSIJ
                   4002:     v1=hess[thetai][thetai];
                   4003:     v2=hess[thetaj][thetaj];
                   4004:     cv12=res;
                   4005:     /* Computing eigen value of Hessian matrix */
                   4006:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4007:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4008:     if ((lc2 <0) || (lc1 <0) ){
                   4009:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4010:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4011:       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);
                   4012:       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);
                   4013:     }
1.126     brouard  4014: #endif
                   4015:   }
                   4016:   return res;
                   4017: }
                   4018: 
1.203     brouard  4019:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4020: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4021: /* { */
                   4022: /*   int i; */
                   4023: /*   int l=1, lmax=20; */
                   4024: /*   double k1,k2,k3,k4,res,fx; */
                   4025: /*   double p2[MAXPARM+1]; */
                   4026: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4027: /*   int k=0,kmax=10; */
                   4028: /*   double l1; */
                   4029:   
                   4030: /*   fx=func(x); */
                   4031: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4032: /*     l1=pow(10,l); */
                   4033: /*     delts=delt; */
                   4034: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4035: /*       delt = delti*(l1*k); */
                   4036: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4037: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4038: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4039: /*       k1=func(p2)-fx; */
                   4040:       
                   4041: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4042: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4043: /*       k2=func(p2)-fx; */
                   4044:       
                   4045: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4046: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4047: /*       k3=func(p2)-fx; */
                   4048:       
                   4049: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4050: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4051: /*       k4=func(p2)-fx; */
                   4052: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4053: /* #ifdef DEBUGHESSIJ */
                   4054: /*       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); */
                   4055: /*       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); */
                   4056: /* #endif */
                   4057: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4058: /*     k=kmax; */
                   4059: /*       } */
                   4060: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4061: /*     k=kmax; l=lmax*10; */
                   4062: /*       } */
                   4063: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4064: /*     delts=delt; */
                   4065: /*       } */
                   4066: /*     } /\* End loop k *\/ */
                   4067: /*   } */
                   4068: /*   delti[theta]=delts; */
                   4069: /*   return res;  */
                   4070: /* } */
                   4071: 
                   4072: 
1.126     brouard  4073: /************** Inverse of matrix **************/
                   4074: void ludcmp(double **a, int n, int *indx, double *d) 
                   4075: { 
                   4076:   int i,imax,j,k; 
                   4077:   double big,dum,sum,temp; 
                   4078:   double *vv; 
                   4079:  
                   4080:   vv=vector(1,n); 
                   4081:   *d=1.0; 
                   4082:   for (i=1;i<=n;i++) { 
                   4083:     big=0.0; 
                   4084:     for (j=1;j<=n;j++) 
                   4085:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   4086:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   4087:     vv[i]=1.0/big; 
                   4088:   } 
                   4089:   for (j=1;j<=n;j++) { 
                   4090:     for (i=1;i<j;i++) { 
                   4091:       sum=a[i][j]; 
                   4092:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4093:       a[i][j]=sum; 
                   4094:     } 
                   4095:     big=0.0; 
                   4096:     for (i=j;i<=n;i++) { 
                   4097:       sum=a[i][j]; 
                   4098:       for (k=1;k<j;k++) 
                   4099:        sum -= a[i][k]*a[k][j]; 
                   4100:       a[i][j]=sum; 
                   4101:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4102:        big=dum; 
                   4103:        imax=i; 
                   4104:       } 
                   4105:     } 
                   4106:     if (j != imax) { 
                   4107:       for (k=1;k<=n;k++) { 
                   4108:        dum=a[imax][k]; 
                   4109:        a[imax][k]=a[j][k]; 
                   4110:        a[j][k]=dum; 
                   4111:       } 
                   4112:       *d = -(*d); 
                   4113:       vv[imax]=vv[j]; 
                   4114:     } 
                   4115:     indx[j]=imax; 
                   4116:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4117:     if (j != n) { 
                   4118:       dum=1.0/(a[j][j]); 
                   4119:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4120:     } 
                   4121:   } 
                   4122:   free_vector(vv,1,n);  /* Doesn't work */
                   4123: ;
                   4124: } 
                   4125: 
                   4126: void lubksb(double **a, int n, int *indx, double b[]) 
                   4127: { 
                   4128:   int i,ii=0,ip,j; 
                   4129:   double sum; 
                   4130:  
                   4131:   for (i=1;i<=n;i++) { 
                   4132:     ip=indx[i]; 
                   4133:     sum=b[ip]; 
                   4134:     b[ip]=b[i]; 
                   4135:     if (ii) 
                   4136:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4137:     else if (sum) ii=i; 
                   4138:     b[i]=sum; 
                   4139:   } 
                   4140:   for (i=n;i>=1;i--) { 
                   4141:     sum=b[i]; 
                   4142:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4143:     b[i]=sum/a[i][i]; 
                   4144:   } 
                   4145: } 
                   4146: 
                   4147: void pstamp(FILE *fichier)
                   4148: {
1.196     brouard  4149:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4150: }
                   4151: 
                   4152: /************ Frequencies ********************/
1.226     brouard  4153: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   4154:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4155:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   4156: {  /* Some frequencies */
                   4157:   
1.227     brouard  4158:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  4159:   int iind=0, iage=0;
                   4160:   int mi; /* Effective wave */
                   4161:   int first;
                   4162:   double ***freq; /* Frequencies */
                   4163:   double *meanq;
                   4164:   double **meanqt;
                   4165:   double *pp, **prop, *posprop, *pospropt;
                   4166:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4167:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4168:   double agebegin, ageend;
                   4169:     
                   4170:   pp=vector(1,nlstate);
                   4171:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4172:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4173:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4174:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4175:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4176:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4177:   strcpy(fileresp,"P_");
                   4178:   strcat(fileresp,fileresu);
                   4179:   /*strcat(fileresphtm,fileresu);*/
                   4180:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4181:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4182:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4183:     exit(0);
                   4184:   }
1.240     brouard  4185:   
1.226     brouard  4186:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4187:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4188:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4189:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4190:     fflush(ficlog);
                   4191:     exit(70); 
                   4192:   }
                   4193:   else{
                   4194:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4195: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4196: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4197:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4198:   }
1.237     brouard  4199:   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  4200:   
1.226     brouard  4201:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4202:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4203:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4204:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4205:     fflush(ficlog);
                   4206:     exit(70); 
1.240     brouard  4207:   } else{
1.226     brouard  4208:     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  4209: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4210: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4211:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4212:   }
1.240     brouard  4213:   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);
                   4214:   
1.226     brouard  4215:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4216:   j1=0;
1.126     brouard  4217:   
1.227     brouard  4218:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4219:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4220:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4221:   
1.226     brouard  4222:   first=1;
1.240     brouard  4223:   
1.226     brouard  4224:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4225:      reference=low_education V1=0,V2=0
                   4226:      med_educ                V1=1 V2=0, 
                   4227:      high_educ               V1=0 V2=1
                   4228:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4229:   */
1.240     brouard  4230:   
1.227     brouard  4231:   for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination in order of model, excluding quantitatives V4=0, V3=0 for example, fixed or varying covariates */
1.226     brouard  4232:     posproptt=0.;
                   4233:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4234:       scanf("%d", i);*/
                   4235:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4236:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.240     brouard  4237:        for(m=iagemin; m <= iagemax+3; m++)
                   4238:          freq[i][jk][m]=0;
                   4239:     
1.226     brouard  4240:     for (i=1; i<=nlstate; i++)  {
                   4241:       for(m=iagemin; m <= iagemax+3; m++)
1.240     brouard  4242:        prop[i][m]=0;
1.226     brouard  4243:       posprop[i]=0;
                   4244:       pospropt[i]=0;
                   4245:     }
1.227     brouard  4246:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4247:     /*   meanq[z1]+=0.; */
                   4248:     /*   for(m=1;m<=lastpass;m++){ */
                   4249:     /*         meanqt[m][z1]=0.; */
                   4250:     /*   } */
                   4251:     /* } */
1.240     brouard  4252:     
1.226     brouard  4253:     dateintsum=0;
                   4254:     k2cpt=0;
1.227     brouard  4255:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4256:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4257:       bool=1;
1.227     brouard  4258:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4259:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4260:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4261:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4262:          /* } */
1.234     brouard  4263:          for (z1=1; z1<=cptcoveff; z1++) {  
                   4264:            /* if(Tvaraff[z1] ==-20){ */
                   4265:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4266:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4267:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4268:            /* }else  */
                   4269:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4270:              /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4271:              bool=0;
                   4272:              /* 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", 
                   4273:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4274:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4275:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4276:            } /* Onlyf fixed */
                   4277:          } /* end z1 */
                   4278:        } /* cptcovn > 0 */
1.227     brouard  4279:       } /* end any */
                   4280:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4281:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4282:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4283:          m=mw[mi][iind];
                   4284:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4285:            for (z1=1; z1<=cptcoveff; z1++) {
                   4286:              if( Fixed[Tmodelind[z1]]==1){
                   4287:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4288:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4289:                  bool=0;
                   4290:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4291:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4292:                  bool=0;
                   4293:                }
                   4294:              }
                   4295:            }
                   4296:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4297:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4298:          if(bool==1){
                   4299:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4300:               and mw[mi+1][iind]. dh depends on stepm. */
                   4301:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4302:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4303:            if(m >=firstpass && m <=lastpass){
                   4304:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4305:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4306:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4307:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4308:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4309:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4310:              if (m<lastpass) {
                   4311:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4312:                /*   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]); */
                   4313:                if(s[m][iind]==-1)
                   4314:                  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.));
                   4315:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4316:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4317:                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 */
                   4318:              }
                   4319:            } /* end if between passes */  
                   4320:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4321:              dateintsum=dateintsum+k2;
                   4322:              k2cpt++;
                   4323:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4324:            }
                   4325:          } /* end bool 2 */
                   4326:        } /* end m */
1.226     brouard  4327:       } /* end bool */
                   4328:     } /* end iind = 1 to imx */
                   4329:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4330:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.240     brouard  4331:     
                   4332:     
1.226     brouard  4333:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4334:     pstamp(ficresp);
1.240     brouard  4335:     if  (cptcoveff>0){
1.226     brouard  4336:       fprintf(ficresp, "\n#********** Variable "); 
                   4337:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4338:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.240     brouard  4339:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4340:       for (z1=1; z1<=cptcoveff; z1++){
1.240     brouard  4341:        if(DummyV[z1]){
                   4342:          fprintf(ficresp, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4343:          fprintf(ficresphtm, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4344:          fprintf(ficresphtmfr, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4345:          fprintf(ficlog, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4346:        }else{
                   4347:          fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4348:          fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4349:          fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4350:          fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4351:        }
1.226     brouard  4352:       }
                   4353:       fprintf(ficresp, "**********\n#");
                   4354:       fprintf(ficresphtm, "**********</h3>\n");
                   4355:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4356:       fprintf(ficlog, "**********\n");
                   4357:     }
                   4358:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4359:     for(i=1; i<=nlstate;i++) {
1.240     brouard  4360:       fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
1.226     brouard  4361:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4362:     }
                   4363:     fprintf(ficresp, "\n");
                   4364:     fprintf(ficresphtm, "\n");
1.240     brouard  4365:     
1.226     brouard  4366:     /* Header of frequency table by age */
                   4367:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4368:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4369:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4370:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4371:        if(jk!=0 && m!=0)
                   4372:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4373:       }
                   4374:     }
                   4375:     fprintf(ficresphtmfr, "\n");
1.240     brouard  4376:     
1.226     brouard  4377:     /* For each age */
                   4378:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4379:       fprintf(ficresphtm,"<tr>");
                   4380:       if(iage==iagemax+1){
1.240     brouard  4381:        fprintf(ficlog,"1");
                   4382:        fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4383:       }else if(iage==iagemax+2){
1.240     brouard  4384:        fprintf(ficlog,"0");
                   4385:        fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4386:       }else if(iage==iagemax+3){
1.240     brouard  4387:        fprintf(ficlog,"Total");
                   4388:        fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4389:       }else{
1.240     brouard  4390:        if(first==1){
                   4391:          first=0;
                   4392:          printf("See log file for details...\n");
                   4393:        }
                   4394:        fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4395:        fprintf(ficlog,"Age %d", iage);
1.226     brouard  4396:       }
                   4397:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4398:        for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4399:          pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4400:       }
                   4401:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4402:        for(m=-1, pos=0; m <=0 ; m++)
                   4403:          pos += freq[jk][m][iage];
                   4404:        if(pp[jk]>=1.e-10){
                   4405:          if(first==1){
                   4406:            printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4407:          }
                   4408:          fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4409:        }else{
                   4410:          if(first==1)
                   4411:            printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4412:          fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4413:        }
1.226     brouard  4414:       }
1.240     brouard  4415:       
1.226     brouard  4416:       for(jk=1; jk <=nlstate ; jk++){ 
1.240     brouard  4417:        /* posprop[jk]=0; */
                   4418:        for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4419:          pp[jk] += freq[jk][m][iage];
1.226     brouard  4420:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.240     brouard  4421:       
1.226     brouard  4422:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.240     brouard  4423:        pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4424:        posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4425:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4426:        pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4427:                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4428:       }
                   4429:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4430:        if(pos>=1.e-5){
                   4431:          if(first==1)
                   4432:            printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4433:          fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4434:        }else{
                   4435:          if(first==1)
                   4436:            printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4437:          fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4438:        }
                   4439:        if( iage <= iagemax){
                   4440:          if(pos>=1.e-5){
                   4441:            fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4442:            fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4443:            /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4444:            /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4445:          }
                   4446:          else{
                   4447:            fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4448:            fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4449:          }
                   4450:        }
                   4451:        pospropt[jk] +=posprop[jk];
1.226     brouard  4452:       } /* end loop jk */
                   4453:       /* pospropt=0.; */
                   4454:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.240     brouard  4455:        for(m=-1; m <=nlstate+ndeath; m++){
                   4456:          if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4457:            if(first==1){
                   4458:              printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4459:            }
                   4460:            fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4461:          }
                   4462:          if(jk!=0 && m!=0)
                   4463:            fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4464:        }
1.226     brouard  4465:       } /* end loop jk */
                   4466:       posproptt=0.; 
                   4467:       for(jk=1; jk <=nlstate; jk++){
1.240     brouard  4468:        posproptt += pospropt[jk];
1.226     brouard  4469:       }
                   4470:       fprintf(ficresphtmfr,"</tr>\n ");
                   4471:       if(iage <= iagemax){
1.240     brouard  4472:        fprintf(ficresp,"\n");
                   4473:        fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4474:       }
                   4475:       if(first==1)
1.240     brouard  4476:        printf("Others in log...\n");
1.226     brouard  4477:       fprintf(ficlog,"\n");
                   4478:     } /* end loop age iage */
                   4479:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4480:     for(jk=1; jk <=nlstate ; jk++){
                   4481:       if(posproptt < 1.e-5){
1.240     brouard  4482:        fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4483:       }else{
1.240     brouard  4484:        fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4485:       }
                   4486:     }
                   4487:     fprintf(ficresphtm,"</tr>\n");
                   4488:     fprintf(ficresphtm,"</table>\n");
                   4489:     fprintf(ficresphtmfr,"</table>\n");
                   4490:     if(posproptt < 1.e-5){
                   4491:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4492:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4493:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4494:       invalidvarcomb[j1]=1;
                   4495:     }else{
                   4496:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4497:       invalidvarcomb[j1]=0;
                   4498:     }
                   4499:     fprintf(ficresphtmfr,"</table>\n");
                   4500:   } /* end selected combination of covariate j1 */
                   4501:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4502:   
1.226     brouard  4503:   fclose(ficresp);
                   4504:   fclose(ficresphtm);
                   4505:   fclose(ficresphtmfr);
                   4506:   free_vector(meanq,1,nqfveff);
                   4507:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4508:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4509:   free_vector(pospropt,1,nlstate);
                   4510:   free_vector(posprop,1,nlstate);
                   4511:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4512:   free_vector(pp,1,nlstate);
                   4513:   /* End of freqsummary */
                   4514: }
1.126     brouard  4515: 
                   4516: /************ Prevalence ********************/
1.227     brouard  4517: 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)
                   4518: {  
                   4519:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4520:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4521:      We still use firstpass and lastpass as another selection.
                   4522:   */
1.126     brouard  4523:  
1.227     brouard  4524:   int i, m, jk, j1, bool, z1,j, iv;
                   4525:   int mi; /* Effective wave */
                   4526:   int iage;
                   4527:   double agebegin, ageend;
                   4528: 
                   4529:   double **prop;
                   4530:   double posprop; 
                   4531:   double  y2; /* in fractional years */
                   4532:   int iagemin, iagemax;
                   4533:   int first; /** to stop verbosity which is redirected to log file */
                   4534: 
                   4535:   iagemin= (int) agemin;
                   4536:   iagemax= (int) agemax;
                   4537:   /*pp=vector(1,nlstate);*/
                   4538:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4539:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4540:   j1=0;
1.222     brouard  4541:   
1.227     brouard  4542:   /*j=cptcoveff;*/
                   4543:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4544:   
1.227     brouard  4545:   first=1;
                   4546:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4547:     for (i=1; i<=nlstate; i++)  
                   4548:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4549:        prop[i][iage]=0.0;
                   4550:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4551:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4552:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4553:     
                   4554:     for (i=1; i<=imx; i++) { /* Each individual */
                   4555:       bool=1;
                   4556:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4557:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4558:        m=mw[mi][i];
                   4559:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4560:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4561:        for (z1=1; z1<=cptcoveff; z1++){
                   4562:          if( Fixed[Tmodelind[z1]]==1){
                   4563:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4564:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4565:              bool=0;
                   4566:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4567:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4568:              bool=0;
                   4569:            }
                   4570:        }
                   4571:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4572:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4573:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4574:          if(m >=firstpass && m <=lastpass){
                   4575:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4576:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4577:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4578:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4579:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4580:                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); 
                   4581:                exit(1);
                   4582:              }
                   4583:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4584:                /*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]]);*/
                   4585:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4586:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4587:              } /* end valid statuses */ 
                   4588:            } /* end selection of dates */
                   4589:          } /* end selection of waves */
                   4590:        } /* end bool */
                   4591:       } /* end wave */
                   4592:     } /* end individual */
                   4593:     for(i=iagemin; i <= iagemax+3; i++){  
                   4594:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4595:        posprop += prop[jk][i]; 
                   4596:       } 
                   4597:       
                   4598:       for(jk=1; jk <=nlstate ; jk++){      
                   4599:        if( i <=  iagemax){ 
                   4600:          if(posprop>=1.e-5){ 
                   4601:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4602:          } else{
                   4603:            if(first==1){
                   4604:              first=0;
                   4605:              printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,j1,probs[i][jk][j1]);
                   4606:            }
                   4607:          }
                   4608:        } 
                   4609:       }/* end jk */ 
                   4610:     }/* end i */ 
1.222     brouard  4611:      /*} *//* end i1 */
1.227     brouard  4612:   } /* end j1 */
1.222     brouard  4613:   
1.227     brouard  4614:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4615:   /*free_vector(pp,1,nlstate);*/
                   4616:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4617: }  /* End of prevalence */
1.126     brouard  4618: 
                   4619: /************* Waves Concatenation ***************/
                   4620: 
                   4621: 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)
                   4622: {
                   4623:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4624:      Death is a valid wave (if date is known).
                   4625:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4626:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4627:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4628:   */
1.126     brouard  4629: 
1.224     brouard  4630:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4631:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4632:      double sum=0., jmean=0.;*/
1.224     brouard  4633:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4634:   int j, k=0,jk, ju, jl;
                   4635:   double sum=0.;
                   4636:   first=0;
1.214     brouard  4637:   firstwo=0;
1.217     brouard  4638:   firsthree=0;
1.218     brouard  4639:   firstfour=0;
1.164     brouard  4640:   jmin=100000;
1.126     brouard  4641:   jmax=-1;
                   4642:   jmean=0.;
1.224     brouard  4643: 
                   4644: /* Treating live states */
1.214     brouard  4645:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4646:     mi=0;  /* First valid wave */
1.227     brouard  4647:     mli=0; /* Last valid wave */
1.126     brouard  4648:     m=firstpass;
1.214     brouard  4649:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4650:       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 */
                   4651:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4652:       }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 */
                   4653:        mw[++mi][i]=m;
                   4654:        mli=m;
1.224     brouard  4655:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4656:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4657:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4658:       }
1.227     brouard  4659:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4660: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4661:        break;
1.224     brouard  4662: #else
1.227     brouard  4663:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4664:          if(firsthree == 0){
                   4665:            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 pi. .\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);
                   4666:            firsthree=1;
                   4667:          }
                   4668:          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 pi. .\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);
                   4669:          mw[++mi][i]=m;
                   4670:          mli=m;
                   4671:        }
                   4672:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4673:          nbwarn++;
                   4674:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4675:            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);
                   4676:            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);
                   4677:          }
                   4678:          break;
                   4679:        }
                   4680:        break;
1.224     brouard  4681: #endif
1.227     brouard  4682:       }/* End m >= lastpass */
1.126     brouard  4683:     }/* end while */
1.224     brouard  4684: 
1.227     brouard  4685:     /* 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  4686:     /* After last pass */
1.224     brouard  4687: /* Treating death states */
1.214     brouard  4688:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4689:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4690:       /* } */
1.126     brouard  4691:       mi++;    /* Death is another wave */
                   4692:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4693:       /* Only death is a correct wave */
1.126     brouard  4694:       mw[mi][i]=m;
1.224     brouard  4695:     }
                   4696: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4697:     else if ((int) andc[i] != 9999) { /* Status is negative. A death occured after lastpass, we can't take it into account because of potential bias */
1.216     brouard  4698:       /* m++; */
                   4699:       /* mi++; */
                   4700:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4701:       /* mw[mi][i]=m; */
1.218     brouard  4702:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4703:        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 */
                   4704:          nbwarn++;
                   4705:          if(firstfiv==0){
                   4706:            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 );
                   4707:            firstfiv=1;
                   4708:          }else{
                   4709:            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 );
                   4710:          }
                   4711:        }else{ /* Death occured afer last wave potential bias */
                   4712:          nberr++;
                   4713:          if(firstwo==0){
                   4714:            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.\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 );
                   4715:            firstwo=1;
                   4716:          }
                   4717:          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.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4718:        }
1.218     brouard  4719:       }else{ /* end date of interview is known */
1.227     brouard  4720:        /* death is known but not confirmed by death status at any wave */
                   4721:        if(firstfour==0){
                   4722:          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 );
                   4723:          firstfour=1;
                   4724:        }
                   4725:        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  4726:       }
1.224     brouard  4727:     } /* end if date of death is known */
                   4728: #endif
                   4729:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4730:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4731:     if(mi==0){
                   4732:       nbwarn++;
                   4733:       if(first==0){
1.227     brouard  4734:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4735:        first=1;
1.126     brouard  4736:       }
                   4737:       if(first==1){
1.227     brouard  4738:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4739:       }
                   4740:     } /* end mi==0 */
                   4741:   } /* End individuals */
1.214     brouard  4742:   /* wav and mw are no more changed */
1.223     brouard  4743:        
1.214     brouard  4744:   
1.126     brouard  4745:   for(i=1; i<=imx; i++){
                   4746:     for(mi=1; mi<wav[i];mi++){
                   4747:       if (stepm <=0)
1.227     brouard  4748:        dh[mi][i]=1;
1.126     brouard  4749:       else{
1.227     brouard  4750:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4751:          if (agedc[i] < 2*AGESUP) {
                   4752:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4753:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4754:            else if(j<0){
                   4755:              nberr++;
                   4756:              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]);
                   4757:              j=1; /* Temporary Dangerous patch */
                   4758:              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);
                   4759:              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]);
                   4760:              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);
                   4761:            }
                   4762:            k=k+1;
                   4763:            if (j >= jmax){
                   4764:              jmax=j;
                   4765:              ijmax=i;
                   4766:            }
                   4767:            if (j <= jmin){
                   4768:              jmin=j;
                   4769:              ijmin=i;
                   4770:            }
                   4771:            sum=sum+j;
                   4772:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4773:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4774:          }
                   4775:        }
                   4776:        else{
                   4777:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4778: /*       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  4779:                                        
1.227     brouard  4780:          k=k+1;
                   4781:          if (j >= jmax) {
                   4782:            jmax=j;
                   4783:            ijmax=i;
                   4784:          }
                   4785:          else if (j <= jmin){
                   4786:            jmin=j;
                   4787:            ijmin=i;
                   4788:          }
                   4789:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4790:          /*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]);*/
                   4791:          if(j<0){
                   4792:            nberr++;
                   4793:            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]);
                   4794:            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]);
                   4795:          }
                   4796:          sum=sum+j;
                   4797:        }
                   4798:        jk= j/stepm;
                   4799:        jl= j -jk*stepm;
                   4800:        ju= j -(jk+1)*stepm;
                   4801:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4802:          if(jl==0){
                   4803:            dh[mi][i]=jk;
                   4804:            bh[mi][i]=0;
                   4805:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4806:                  * to avoid the price of an extra matrix product in likelihood */
                   4807:            dh[mi][i]=jk+1;
                   4808:            bh[mi][i]=ju;
                   4809:          }
                   4810:        }else{
                   4811:          if(jl <= -ju){
                   4812:            dh[mi][i]=jk;
                   4813:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4814:                                 * is higher than the multiple of stepm and negative otherwise.
                   4815:                                 */
                   4816:          }
                   4817:          else{
                   4818:            dh[mi][i]=jk+1;
                   4819:            bh[mi][i]=ju;
                   4820:          }
                   4821:          if(dh[mi][i]==0){
                   4822:            dh[mi][i]=1; /* At least one step */
                   4823:            bh[mi][i]=ju; /* At least one step */
                   4824:            /*  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);*/
                   4825:          }
                   4826:        } /* end if mle */
1.126     brouard  4827:       }
                   4828:     } /* end wave */
                   4829:   }
                   4830:   jmean=sum/k;
                   4831:   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  4832:   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  4833: }
1.126     brouard  4834: 
                   4835: /*********** Tricode ****************************/
1.220     brouard  4836:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242   ! brouard  4837:  {
        !          4838:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
        !          4839:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
        !          4840:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
        !          4841:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
        !          4842:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
        !          4843:     */
1.130     brouard  4844: 
1.242   ! brouard  4845:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
        !          4846:    int modmaxcovj=0; /* Modality max of covariates j */
        !          4847:    int cptcode=0; /* Modality max of covariates j */
        !          4848:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  4849: 
                   4850: 
1.242   ! brouard  4851:    /* cptcoveff=0;  */
        !          4852:    /* *cptcov=0; */
1.126     brouard  4853:  
1.242   ! brouard  4854:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4855: 
1.242   ! brouard  4856:    /* Loop on covariates without age and products and no quantitative variable */
        !          4857:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
        !          4858:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
        !          4859:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
        !          4860:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
        !          4861:        switch(Fixed[k]) {
        !          4862:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
        !          4863:         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*/
        !          4864:           ij=(int)(covar[Tvar[k]][i]);
        !          4865:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
        !          4866:            * If product of Vn*Vm, still boolean *:
        !          4867:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
        !          4868:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
        !          4869:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
        !          4870:              modality of the nth covariate of individual i. */
        !          4871:           if (ij > modmaxcovj)
        !          4872:             modmaxcovj=ij; 
        !          4873:           else if (ij < modmincovj) 
        !          4874:             modmincovj=ij; 
        !          4875:           if ((ij < -1) && (ij > NCOVMAX)){
        !          4876:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
        !          4877:             exit(1);
        !          4878:           }else
        !          4879:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
        !          4880:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
        !          4881:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
        !          4882:           /* getting the maximum value of the modality of the covariate
        !          4883:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
        !          4884:              female ies 1, then modmaxcovj=1.
        !          4885:           */
        !          4886:         } /* end for loop on individuals i */
        !          4887:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
        !          4888:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
        !          4889:         cptcode=modmaxcovj;
        !          4890:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
        !          4891:         /*for (i=0; i<=cptcode; i++) {*/
        !          4892:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
        !          4893:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
        !          4894:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
        !          4895:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
        !          4896:             if( j != -1){
        !          4897:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
        !          4898:                                  covariate for which somebody answered excluding 
        !          4899:                                  undefined. Usually 2: 0 and 1. */
        !          4900:             }
        !          4901:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
        !          4902:                                     covariate for which somebody answered including 
        !          4903:                                     undefined. Usually 3: -1, 0 and 1. */
        !          4904:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
        !          4905:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
        !          4906:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  4907:                        
1.242   ! brouard  4908:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
        !          4909:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
        !          4910:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
        !          4911:         /* modmincovj=3; modmaxcovj = 7; */
        !          4912:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
        !          4913:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
        !          4914:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
        !          4915:         /* nbcode[Tvar[j]][ij]=k; */
        !          4916:         /* nbcode[Tvar[j]][1]=0; */
        !          4917:         /* nbcode[Tvar[j]][2]=1; */
        !          4918:         /* nbcode[Tvar[j]][3]=2; */
        !          4919:         /* To be continued (not working yet). */
        !          4920:         ij=0; /* ij is similar to i but can jump over null modalities */
        !          4921:         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*/
        !          4922:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
        !          4923:             break;
        !          4924:           }
        !          4925:           ij++;
        !          4926:           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*/
        !          4927:           cptcode = ij; /* New max modality for covar j */
        !          4928:         } /* end of loop on modality i=-1 to 1 or more */
        !          4929:         break;
        !          4930:        case 1: /* Testing on varying covariate, could be simple and
        !          4931:                * should look at waves or product of fixed *
        !          4932:                * varying. No time to test -1, assuming 0 and 1 only */
        !          4933:         ij=0;
        !          4934:         for(i=0; i<=1;i++){
        !          4935:           nbcode[Tvar[k]][++ij]=i;
        !          4936:         }
        !          4937:         break;
        !          4938:        default:
        !          4939:         break;
        !          4940:        } /* end switch */
        !          4941:      } /* end dummy test */
        !          4942:     
        !          4943:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
        !          4944:      /*        /\*recode from 0 *\/ */
        !          4945:      /*                                     k is a modality. If we have model=V1+V1*sex  */
        !          4946:      /*                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
        !          4947:      /*                                  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
        !          4948:      /*        } */
        !          4949:      /*        /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
        !          4950:      /*        if (ij > ncodemax[j]) { */
        !          4951:      /*          printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
        !          4952:      /*          fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
        !          4953:      /*          break; */
        !          4954:      /*        } */
        !          4955:      /*   }  /\* end of loop on modality k *\/ */
        !          4956:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
        !          4957:   
        !          4958:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
        !          4959:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
        !          4960:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
        !          4961:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
        !          4962:      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 */ 
        !          4963:      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 */
        !          4964:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
        !          4965:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
        !          4966:   
        !          4967:    ij=0;
        !          4968:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
        !          4969:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
        !          4970:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
        !          4971:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
        !          4972:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
        !          4973:        /* If product not in single variable we don't print results */
        !          4974:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
        !          4975:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
        !          4976:        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*/
        !          4977:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
        !          4978:        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 */
        !          4979:        if(Fixed[k]!=0)
        !          4980:         anyvaryingduminmodel=1;
        !          4981:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
        !          4982:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
        !          4983:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
        !          4984:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
        !          4985:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
        !          4986:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
        !          4987:      } 
        !          4988:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
        !          4989:    /* ij--; */
        !          4990:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
        !          4991:    *cptcov=ij; /*Number of total real effective covariates: effective
        !          4992:                * because they can be excluded from the model and real
        !          4993:                * if in the model but excluded because missing values, but how to get k from ij?*/
        !          4994:    for(j=ij+1; j<= cptcovt; j++){
        !          4995:      Tvaraff[j]=0;
        !          4996:      Tmodelind[j]=0;
        !          4997:    }
        !          4998:    for(j=ntveff+1; j<= cptcovt; j++){
        !          4999:      TmodelInvind[j]=0;
        !          5000:    }
        !          5001:    /* To be sorted */
        !          5002:    ;
        !          5003:  }
1.126     brouard  5004: 
1.145     brouard  5005: 
1.126     brouard  5006: /*********** Health Expectancies ****************/
                   5007: 
1.235     brouard  5008:  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  5009: 
                   5010: {
                   5011:   /* Health expectancies, no variances */
1.164     brouard  5012:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5013:   int nhstepma, nstepma; /* Decreasing with age */
                   5014:   double age, agelim, hf;
                   5015:   double ***p3mat;
                   5016:   double eip;
                   5017: 
1.238     brouard  5018:   /* pstamp(ficreseij); */
1.126     brouard  5019:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5020:   fprintf(ficreseij,"# Age");
                   5021:   for(i=1; i<=nlstate;i++){
                   5022:     for(j=1; j<=nlstate;j++){
                   5023:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5024:     }
                   5025:     fprintf(ficreseij," e%1d. ",i);
                   5026:   }
                   5027:   fprintf(ficreseij,"\n");
                   5028: 
                   5029:   
                   5030:   if(estepm < stepm){
                   5031:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5032:   }
                   5033:   else  hstepm=estepm;   
                   5034:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5035:    * This is mainly to measure the difference between two models: for example
                   5036:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5037:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5038:    * progression in between and thus overestimating or underestimating according
                   5039:    * to the curvature of the survival function. If, for the same date, we 
                   5040:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5041:    * to compare the new estimate of Life expectancy with the same linear 
                   5042:    * hypothesis. A more precise result, taking into account a more precise
                   5043:    * curvature will be obtained if estepm is as small as stepm. */
                   5044: 
                   5045:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5046:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5047:      nhstepm is the number of hstepm from age to agelim 
                   5048:      nstepm is the number of stepm from age to agelin. 
                   5049:      Look at hpijx to understand the reason of that which relies in memory size
                   5050:      and note for a fixed period like estepm months */
                   5051:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5052:      survival function given by stepm (the optimization length). Unfortunately it
                   5053:      means that if the survival funtion is printed only each two years of age and if
                   5054:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5055:      results. So we changed our mind and took the option of the best precision.
                   5056:   */
                   5057:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5058: 
                   5059:   agelim=AGESUP;
                   5060:   /* If stepm=6 months */
                   5061:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5062:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5063:     
                   5064: /* nhstepm age range expressed in number of stepm */
                   5065:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5066:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5067:   /* if (stepm >= YEARM) hstepm=1;*/
                   5068:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5069:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5070: 
                   5071:   for (age=bage; age<=fage; age ++){ 
                   5072:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5073:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5074:     /* if (stepm >= YEARM) hstepm=1;*/
                   5075:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5076: 
                   5077:     /* If stepm=6 months */
                   5078:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5079:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5080:     
1.235     brouard  5081:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5082:     
                   5083:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5084:     
                   5085:     printf("%d|",(int)age);fflush(stdout);
                   5086:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5087:     
                   5088:     /* Computing expectancies */
                   5089:     for(i=1; i<=nlstate;i++)
                   5090:       for(j=1; j<=nlstate;j++)
                   5091:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5092:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5093:          
                   5094:          /* 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]);*/
                   5095: 
                   5096:        }
                   5097: 
                   5098:     fprintf(ficreseij,"%3.0f",age );
                   5099:     for(i=1; i<=nlstate;i++){
                   5100:       eip=0;
                   5101:       for(j=1; j<=nlstate;j++){
                   5102:        eip +=eij[i][j][(int)age];
                   5103:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5104:       }
                   5105:       fprintf(ficreseij,"%9.4f", eip );
                   5106:     }
                   5107:     fprintf(ficreseij,"\n");
                   5108:     
                   5109:   }
                   5110:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5111:   printf("\n");
                   5112:   fprintf(ficlog,"\n");
                   5113:   
                   5114: }
                   5115: 
1.235     brouard  5116:  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  5117: 
                   5118: {
                   5119:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5120:      to initial status i, ei. .
1.126     brouard  5121:   */
                   5122:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5123:   int nhstepma, nstepma; /* Decreasing with age */
                   5124:   double age, agelim, hf;
                   5125:   double ***p3matp, ***p3matm, ***varhe;
                   5126:   double **dnewm,**doldm;
                   5127:   double *xp, *xm;
                   5128:   double **gp, **gm;
                   5129:   double ***gradg, ***trgradg;
                   5130:   int theta;
                   5131: 
                   5132:   double eip, vip;
                   5133: 
                   5134:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5135:   xp=vector(1,npar);
                   5136:   xm=vector(1,npar);
                   5137:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5138:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5139:   
                   5140:   pstamp(ficresstdeij);
                   5141:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5142:   fprintf(ficresstdeij,"# Age");
                   5143:   for(i=1; i<=nlstate;i++){
                   5144:     for(j=1; j<=nlstate;j++)
                   5145:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5146:     fprintf(ficresstdeij," e%1d. ",i);
                   5147:   }
                   5148:   fprintf(ficresstdeij,"\n");
                   5149: 
                   5150:   pstamp(ficrescveij);
                   5151:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5152:   fprintf(ficrescveij,"# Age");
                   5153:   for(i=1; i<=nlstate;i++)
                   5154:     for(j=1; j<=nlstate;j++){
                   5155:       cptj= (j-1)*nlstate+i;
                   5156:       for(i2=1; i2<=nlstate;i2++)
                   5157:        for(j2=1; j2<=nlstate;j2++){
                   5158:          cptj2= (j2-1)*nlstate+i2;
                   5159:          if(cptj2 <= cptj)
                   5160:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5161:        }
                   5162:     }
                   5163:   fprintf(ficrescveij,"\n");
                   5164:   
                   5165:   if(estepm < stepm){
                   5166:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5167:   }
                   5168:   else  hstepm=estepm;   
                   5169:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5170:    * This is mainly to measure the difference between two models: for example
                   5171:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5172:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5173:    * progression in between and thus overestimating or underestimating according
                   5174:    * to the curvature of the survival function. If, for the same date, we 
                   5175:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5176:    * to compare the new estimate of Life expectancy with the same linear 
                   5177:    * hypothesis. A more precise result, taking into account a more precise
                   5178:    * curvature will be obtained if estepm is as small as stepm. */
                   5179: 
                   5180:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5181:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5182:      nhstepm is the number of hstepm from age to agelim 
                   5183:      nstepm is the number of stepm from age to agelin. 
                   5184:      Look at hpijx to understand the reason of that which relies in memory size
                   5185:      and note for a fixed period like estepm months */
                   5186:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5187:      survival function given by stepm (the optimization length). Unfortunately it
                   5188:      means that if the survival funtion is printed only each two years of age and if
                   5189:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5190:      results. So we changed our mind and took the option of the best precision.
                   5191:   */
                   5192:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5193: 
                   5194:   /* If stepm=6 months */
                   5195:   /* nhstepm age range expressed in number of stepm */
                   5196:   agelim=AGESUP;
                   5197:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5198:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5199:   /* if (stepm >= YEARM) hstepm=1;*/
                   5200:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5201:   
                   5202:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5203:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5204:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5205:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5206:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5207:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5208: 
                   5209:   for (age=bage; age<=fage; age ++){ 
                   5210:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5211:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5212:     /* if (stepm >= YEARM) hstepm=1;*/
                   5213:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5214:                
1.126     brouard  5215:     /* If stepm=6 months */
                   5216:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5217:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5218:     
                   5219:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5220:                
1.126     brouard  5221:     /* Computing  Variances of health expectancies */
                   5222:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5223:        decrease memory allocation */
                   5224:     for(theta=1; theta <=npar; theta++){
                   5225:       for(i=1; i<=npar; i++){ 
1.222     brouard  5226:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5227:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5228:       }
1.235     brouard  5229:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5230:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5231:                        
1.126     brouard  5232:       for(j=1; j<= nlstate; j++){
1.222     brouard  5233:        for(i=1; i<=nlstate; i++){
                   5234:          for(h=0; h<=nhstepm-1; h++){
                   5235:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5236:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5237:          }
                   5238:        }
1.126     brouard  5239:       }
1.218     brouard  5240:                        
1.126     brouard  5241:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5242:        for(h=0; h<=nhstepm-1; h++){
                   5243:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5244:        }
1.126     brouard  5245:     }/* End theta */
                   5246:     
                   5247:     
                   5248:     for(h=0; h<=nhstepm-1; h++)
                   5249:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5250:        for(theta=1; theta <=npar; theta++)
                   5251:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5252:     
1.218     brouard  5253:                
1.222     brouard  5254:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5255:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5256:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5257:                
1.222     brouard  5258:     printf("%d|",(int)age);fflush(stdout);
                   5259:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5260:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5261:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5262:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5263:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5264:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5265:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5266:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5267:       }
                   5268:     }
1.218     brouard  5269:                
1.126     brouard  5270:     /* Computing expectancies */
1.235     brouard  5271:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5272:     for(i=1; i<=nlstate;i++)
                   5273:       for(j=1; j<=nlstate;j++)
1.222     brouard  5274:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5275:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5276:                                        
1.222     brouard  5277:          /* 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  5278:                                        
1.222     brouard  5279:        }
1.218     brouard  5280:                
1.126     brouard  5281:     fprintf(ficresstdeij,"%3.0f",age );
                   5282:     for(i=1; i<=nlstate;i++){
                   5283:       eip=0.;
                   5284:       vip=0.;
                   5285:       for(j=1; j<=nlstate;j++){
1.222     brouard  5286:        eip += eij[i][j][(int)age];
                   5287:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5288:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5289:        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  5290:       }
                   5291:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5292:     }
                   5293:     fprintf(ficresstdeij,"\n");
1.218     brouard  5294:                
1.126     brouard  5295:     fprintf(ficrescveij,"%3.0f",age );
                   5296:     for(i=1; i<=nlstate;i++)
                   5297:       for(j=1; j<=nlstate;j++){
1.222     brouard  5298:        cptj= (j-1)*nlstate+i;
                   5299:        for(i2=1; i2<=nlstate;i2++)
                   5300:          for(j2=1; j2<=nlstate;j2++){
                   5301:            cptj2= (j2-1)*nlstate+i2;
                   5302:            if(cptj2 <= cptj)
                   5303:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5304:          }
1.126     brouard  5305:       }
                   5306:     fprintf(ficrescveij,"\n");
1.218     brouard  5307:                
1.126     brouard  5308:   }
                   5309:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5310:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5311:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5312:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5313:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5314:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5315:   printf("\n");
                   5316:   fprintf(ficlog,"\n");
1.218     brouard  5317:        
1.126     brouard  5318:   free_vector(xm,1,npar);
                   5319:   free_vector(xp,1,npar);
                   5320:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5321:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5322:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5323: }
1.218     brouard  5324:  
1.126     brouard  5325: /************ Variance ******************/
1.235     brouard  5326:  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  5327:  {
                   5328:    /* Variance of health expectancies */
                   5329:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5330:    /* double **newm;*/
                   5331:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5332:   
                   5333:    /* int movingaverage(); */
                   5334:    double **dnewm,**doldm;
                   5335:    double **dnewmp,**doldmp;
                   5336:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5337:    int k;
                   5338:    double *xp;
                   5339:    double **gp, **gm;  /* for var eij */
                   5340:    double ***gradg, ***trgradg; /*for var eij */
                   5341:    double **gradgp, **trgradgp; /* for var p point j */
                   5342:    double *gpp, *gmp; /* for var p point j */
                   5343:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5344:    double ***p3mat;
                   5345:    double age,agelim, hf;
                   5346:    /* double ***mobaverage; */
                   5347:    int theta;
                   5348:    char digit[4];
                   5349:    char digitp[25];
                   5350: 
                   5351:    char fileresprobmorprev[FILENAMELENGTH];
                   5352: 
                   5353:    if(popbased==1){
                   5354:      if(mobilav!=0)
                   5355:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5356:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5357:    }
                   5358:    else 
                   5359:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5360: 
1.218     brouard  5361:    /* if (mobilav!=0) { */
                   5362:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5363:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5364:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5365:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5366:    /*   } */
                   5367:    /* } */
                   5368: 
                   5369:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5370:    sprintf(digit,"%-d",ij);
                   5371:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5372:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5373:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5374:    strcat(fileresprobmorprev,fileresu);
                   5375:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5376:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5377:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5378:    }
                   5379:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5380:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5381:    pstamp(ficresprobmorprev);
                   5382:    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  5383:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5384:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5385:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5386:    }
                   5387:    for(j=1;j<=cptcoveff;j++) 
                   5388:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5389:    fprintf(ficresprobmorprev,"\n");
                   5390: 
1.218     brouard  5391:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5392:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5393:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5394:      for(i=1; i<=nlstate;i++)
                   5395:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5396:    }  
                   5397:    fprintf(ficresprobmorprev,"\n");
                   5398:   
                   5399:    fprintf(ficgp,"\n# Routine varevsij");
                   5400:    fprintf(ficgp,"\nunset title \n");
                   5401:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5402:    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");
                   5403:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5404:    /*   } */
                   5405:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5406:    pstamp(ficresvij);
                   5407:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5408:    if(popbased==1)
                   5409:      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);
                   5410:    else
                   5411:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5412:    fprintf(ficresvij,"# Age");
                   5413:    for(i=1; i<=nlstate;i++)
                   5414:      for(j=1; j<=nlstate;j++)
                   5415:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5416:    fprintf(ficresvij,"\n");
                   5417: 
                   5418:    xp=vector(1,npar);
                   5419:    dnewm=matrix(1,nlstate,1,npar);
                   5420:    doldm=matrix(1,nlstate,1,nlstate);
                   5421:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5422:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5423: 
                   5424:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5425:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5426:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5427:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5428:   
1.218     brouard  5429:    if(estepm < stepm){
                   5430:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5431:    }
                   5432:    else  hstepm=estepm;   
                   5433:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5434:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5435:       nhstepm is the number of hstepm from age to agelim 
                   5436:       nstepm is the number of stepm from age to agelim. 
                   5437:       Look at function hpijx to understand why because of memory size limitations, 
                   5438:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5439:       survival function given by stepm (the optimization length). Unfortunately it
                   5440:       means that if the survival funtion is printed every two years of age and if
                   5441:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5442:       results. So we changed our mind and took the option of the best precision.
                   5443:    */
                   5444:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5445:    agelim = AGESUP;
                   5446:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5447:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5448:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5449:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5450:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5451:      gp=matrix(0,nhstepm,1,nlstate);
                   5452:      gm=matrix(0,nhstepm,1,nlstate);
                   5453:                
                   5454:                
                   5455:      for(theta=1; theta <=npar; theta++){
                   5456:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5457:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5458:        }
                   5459:                        
1.242   ! brouard  5460:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5461:                        
                   5462:        if (popbased==1) {
                   5463:         if(mobilav ==0){
                   5464:           for(i=1; i<=nlstate;i++)
                   5465:             prlim[i][i]=probs[(int)age][i][ij];
                   5466:         }else{ /* mobilav */ 
                   5467:           for(i=1; i<=nlstate;i++)
                   5468:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5469:         }
                   5470:        }
                   5471:                        
1.235     brouard  5472:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.218     brouard  5473:        for(j=1; j<= nlstate; j++){
                   5474:         for(h=0; h<=nhstepm; h++){
                   5475:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5476:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5477:         }
                   5478:        }
                   5479:        /* Next for computing probability of death (h=1 means
                   5480:          computed over hstepm matrices product = hstepm*stepm months) 
                   5481:          as a weighted average of prlim.
                   5482:        */
                   5483:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5484:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5485:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5486:        }    
                   5487:        /* end probability of death */
                   5488:                        
                   5489:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5490:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5491:                        
1.242   ! brouard  5492:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  5493:                        
                   5494:        if (popbased==1) {
                   5495:         if(mobilav ==0){
                   5496:           for(i=1; i<=nlstate;i++)
                   5497:             prlim[i][i]=probs[(int)age][i][ij];
                   5498:         }else{ /* mobilav */ 
                   5499:           for(i=1; i<=nlstate;i++)
                   5500:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5501:         }
                   5502:        }
                   5503:                        
1.235     brouard  5504:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5505:                        
                   5506:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5507:         for(h=0; h<=nhstepm; h++){
                   5508:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5509:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5510:         }
                   5511:        }
                   5512:        /* This for computing probability of death (h=1 means
                   5513:          computed over hstepm matrices product = hstepm*stepm months) 
                   5514:          as a weighted average of prlim.
                   5515:        */
                   5516:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5517:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5518:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5519:        }    
                   5520:        /* end probability of death */
                   5521:                        
                   5522:        for(j=1; j<= nlstate; j++) /* vareij */
                   5523:         for(h=0; h<=nhstepm; h++){
                   5524:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5525:         }
                   5526:                        
                   5527:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5528:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5529:        }
                   5530:                        
                   5531:      } /* End theta */
                   5532:                
                   5533:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5534:                
                   5535:      for(h=0; h<=nhstepm; h++) /* veij */
                   5536:        for(j=1; j<=nlstate;j++)
                   5537:         for(theta=1; theta <=npar; theta++)
                   5538:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5539:                
                   5540:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5541:        for(theta=1; theta <=npar; theta++)
                   5542:         trgradgp[j][theta]=gradgp[theta][j];
                   5543:                
                   5544:                
                   5545:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5546:      for(i=1;i<=nlstate;i++)
                   5547:        for(j=1;j<=nlstate;j++)
                   5548:         vareij[i][j][(int)age] =0.;
                   5549:                
                   5550:      for(h=0;h<=nhstepm;h++){
                   5551:        for(k=0;k<=nhstepm;k++){
                   5552:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5553:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5554:         for(i=1;i<=nlstate;i++)
                   5555:           for(j=1;j<=nlstate;j++)
                   5556:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5557:        }
                   5558:      }
                   5559:                
                   5560:      /* pptj */
                   5561:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5562:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5563:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5564:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5565:         varppt[j][i]=doldmp[j][i];
                   5566:      /* end ppptj */
                   5567:      /*  x centered again */
                   5568:                
1.242   ! brouard  5569:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5570:                
                   5571:      if (popbased==1) {
                   5572:        if(mobilav ==0){
                   5573:         for(i=1; i<=nlstate;i++)
                   5574:           prlim[i][i]=probs[(int)age][i][ij];
                   5575:        }else{ /* mobilav */ 
                   5576:         for(i=1; i<=nlstate;i++)
                   5577:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5578:        }
                   5579:      }
                   5580:                
                   5581:      /* This for computing probability of death (h=1 means
                   5582:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5583:        as a weighted average of prlim.
                   5584:      */
1.235     brouard  5585:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5586:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5587:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5588:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5589:      }    
                   5590:      /* end probability of death */
                   5591:                
                   5592:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5593:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5594:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5595:        for(i=1; i<=nlstate;i++){
                   5596:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5597:        }
                   5598:      } 
                   5599:      fprintf(ficresprobmorprev,"\n");
                   5600:                
                   5601:      fprintf(ficresvij,"%.0f ",age );
                   5602:      for(i=1; i<=nlstate;i++)
                   5603:        for(j=1; j<=nlstate;j++){
                   5604:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5605:        }
                   5606:      fprintf(ficresvij,"\n");
                   5607:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5608:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5609:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5610:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5611:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5612:    } /* End age */
                   5613:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5614:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5615:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5616:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5617:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5618:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5619:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5620:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5621:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5622:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5623:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5624:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5625:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5626:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5627:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5628:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5629:    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);
                   5630:    /*  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  5631:     */
1.218     brouard  5632:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5633:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5634: 
1.218     brouard  5635:    free_vector(xp,1,npar);
                   5636:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5637:    free_matrix(dnewm,1,nlstate,1,npar);
                   5638:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5639:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5640:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5641:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5642:    fclose(ficresprobmorprev);
                   5643:    fflush(ficgp);
                   5644:    fflush(fichtm); 
                   5645:  }  /* end varevsij */
1.126     brouard  5646: 
                   5647: /************ Variance of prevlim ******************/
1.235     brouard  5648:  void varprevlim(char fileres[], 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  5649: {
1.205     brouard  5650:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5651:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5652: 
1.126     brouard  5653:   double **dnewm,**doldm;
                   5654:   int i, j, nhstepm, hstepm;
                   5655:   double *xp;
                   5656:   double *gp, *gm;
                   5657:   double **gradg, **trgradg;
1.208     brouard  5658:   double **mgm, **mgp;
1.126     brouard  5659:   double age,agelim;
                   5660:   int theta;
                   5661:   
                   5662:   pstamp(ficresvpl);
                   5663:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
1.241     brouard  5664:   fprintf(ficresvpl,"# Age ");
                   5665:   if(nresult >=1)
                   5666:     fprintf(ficresvpl," Result# ");
1.126     brouard  5667:   for(i=1; i<=nlstate;i++)
                   5668:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5669:   fprintf(ficresvpl,"\n");
                   5670: 
                   5671:   xp=vector(1,npar);
                   5672:   dnewm=matrix(1,nlstate,1,npar);
                   5673:   doldm=matrix(1,nlstate,1,nlstate);
                   5674:   
                   5675:   hstepm=1*YEARM; /* Every year of age */
                   5676:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5677:   agelim = AGESUP;
                   5678:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5679:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5680:     if (stepm >= YEARM) hstepm=1;
                   5681:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5682:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5683:     mgp=matrix(1,npar,1,nlstate);
                   5684:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5685:     gp=vector(1,nlstate);
                   5686:     gm=vector(1,nlstate);
                   5687: 
                   5688:     for(theta=1; theta <=npar; theta++){
                   5689:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5690:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5691:       }
1.209     brouard  5692:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5693:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5694:       else
1.235     brouard  5695:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5696:       for(i=1;i<=nlstate;i++){
1.126     brouard  5697:        gp[i] = prlim[i][i];
1.208     brouard  5698:        mgp[theta][i] = prlim[i][i];
                   5699:       }
1.126     brouard  5700:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5701:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5702:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5703:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5704:       else
1.235     brouard  5705:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5706:       for(i=1;i<=nlstate;i++){
1.126     brouard  5707:        gm[i] = prlim[i][i];
1.208     brouard  5708:        mgm[theta][i] = prlim[i][i];
                   5709:       }
1.126     brouard  5710:       for(i=1;i<=nlstate;i++)
                   5711:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5712:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5713:     } /* End theta */
                   5714: 
                   5715:     trgradg =matrix(1,nlstate,1,npar);
                   5716: 
                   5717:     for(j=1; j<=nlstate;j++)
                   5718:       for(theta=1; theta <=npar; theta++)
                   5719:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5720:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5721:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5722:     /*   for(j=1; j<=nlstate;j++){ */
                   5723:     /*         printf(" %d ",j); */
                   5724:     /*         for(theta=1; theta <=npar; theta++) */
                   5725:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5726:     /*         printf("\n "); */
                   5727:     /*   } */
                   5728:     /* } */
                   5729:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5730:     /*   printf("\n gradg %d ",(int)age); */
                   5731:     /*   for(j=1; j<=nlstate;j++){ */
                   5732:     /*         printf("%d ",j); */
                   5733:     /*         for(theta=1; theta <=npar; theta++) */
                   5734:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5735:     /*         printf("\n "); */
                   5736:     /*   } */
                   5737:     /* } */
1.126     brouard  5738: 
                   5739:     for(i=1;i<=nlstate;i++)
                   5740:       varpl[i][(int)age] =0.;
1.209     brouard  5741:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5742:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5743:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5744:     }else{
1.126     brouard  5745:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5746:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5747:     }
1.126     brouard  5748:     for(i=1;i<=nlstate;i++)
                   5749:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5750: 
                   5751:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  5752:     if(nresult >=1)
                   5753:       fprintf(ficresvpl,"%d ",nres );
1.126     brouard  5754:     for(i=1; i<=nlstate;i++)
                   5755:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5756:     fprintf(ficresvpl,"\n");
                   5757:     free_vector(gp,1,nlstate);
                   5758:     free_vector(gm,1,nlstate);
1.208     brouard  5759:     free_matrix(mgm,1,npar,1,nlstate);
                   5760:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5761:     free_matrix(gradg,1,npar,1,nlstate);
                   5762:     free_matrix(trgradg,1,nlstate,1,npar);
                   5763:   } /* End age */
                   5764: 
                   5765:   free_vector(xp,1,npar);
                   5766:   free_matrix(doldm,1,nlstate,1,npar);
                   5767:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5768: 
                   5769: }
                   5770: 
                   5771: /************ Variance of one-step probabilities  ******************/
                   5772: 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  5773:  {
                   5774:    int i, j=0,  k1, l1, tj;
                   5775:    int k2, l2, j1,  z1;
                   5776:    int k=0, l;
                   5777:    int first=1, first1, first2;
                   5778:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5779:    double **dnewm,**doldm;
                   5780:    double *xp;
                   5781:    double *gp, *gm;
                   5782:    double **gradg, **trgradg;
                   5783:    double **mu;
                   5784:    double age, cov[NCOVMAX+1];
                   5785:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5786:    int theta;
                   5787:    char fileresprob[FILENAMELENGTH];
                   5788:    char fileresprobcov[FILENAMELENGTH];
                   5789:    char fileresprobcor[FILENAMELENGTH];
                   5790:    double ***varpij;
                   5791: 
                   5792:    strcpy(fileresprob,"PROB_"); 
                   5793:    strcat(fileresprob,fileres);
                   5794:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5795:      printf("Problem with resultfile: %s\n", fileresprob);
                   5796:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5797:    }
                   5798:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5799:    strcat(fileresprobcov,fileresu);
                   5800:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5801:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5802:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5803:    }
                   5804:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5805:    strcat(fileresprobcor,fileresu);
                   5806:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5807:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5808:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5809:    }
                   5810:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5811:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5812:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5813:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5814:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5815:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5816:    pstamp(ficresprob);
                   5817:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5818:    fprintf(ficresprob,"# Age");
                   5819:    pstamp(ficresprobcov);
                   5820:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5821:    fprintf(ficresprobcov,"# Age");
                   5822:    pstamp(ficresprobcor);
                   5823:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5824:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5825: 
                   5826: 
1.222     brouard  5827:    for(i=1; i<=nlstate;i++)
                   5828:      for(j=1; j<=(nlstate+ndeath);j++){
                   5829:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5830:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5831:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5832:      }  
                   5833:    /* fprintf(ficresprob,"\n");
                   5834:       fprintf(ficresprobcov,"\n");
                   5835:       fprintf(ficresprobcor,"\n");
                   5836:    */
                   5837:    xp=vector(1,npar);
                   5838:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5839:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5840:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5841:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5842:    first=1;
                   5843:    fprintf(ficgp,"\n# Routine varprob");
                   5844:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5845:    fprintf(fichtm,"\n");
                   5846: 
                   5847:    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.</li>\n",optionfilehtmcov);
                   5848:    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);
                   5849:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5850: and drawn. It helps understanding how is the covariance between two incidences.\
                   5851:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5852:    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  5853: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5854: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5855: standard deviations wide on each axis. <br>\
                   5856:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5857:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5858: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5859: 
1.222     brouard  5860:    cov[1]=1;
                   5861:    /* tj=cptcoveff; */
1.225     brouard  5862:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5863:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5864:    j1=0;
1.224     brouard  5865:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5866:      if  (cptcovn>0) {
                   5867:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5868:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5869:        fprintf(ficresprob, "**********\n#\n");
                   5870:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5871:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5872:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5873:                        
1.222     brouard  5874:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5875:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5876:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5877:                        
                   5878:                        
1.222     brouard  5879:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5880:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5881:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5882:                        
1.222     brouard  5883:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5884:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5885:        fprintf(ficresprobcor, "**********\n#");    
                   5886:        if(invalidvarcomb[j1]){
                   5887:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5888:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5889:         continue;
                   5890:        }
                   5891:      }
                   5892:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5893:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5894:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5895:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5896:      for (age=bage; age<=fage; age ++){ 
                   5897:        cov[2]=age;
                   5898:        if(nagesqr==1)
                   5899:         cov[3]= age*age;
                   5900:        for (k=1; k<=cptcovn;k++) {
                   5901:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5902:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5903:                                                                    * 1  1 1 1 1
                   5904:                                                                    * 2  2 1 1 1
                   5905:                                                                    * 3  1 2 1 1
                   5906:                                                                    */
                   5907:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5908:        }
                   5909:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5910:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5911:        for (k=1; k<=cptcovprod;k++)
                   5912:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5913:                        
                   5914:                        
1.222     brouard  5915:        for(theta=1; theta <=npar; theta++){
                   5916:         for(i=1; i<=npar; i++)
                   5917:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5918:                                
1.222     brouard  5919:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5920:                                
1.222     brouard  5921:         k=0;
                   5922:         for(i=1; i<= (nlstate); i++){
                   5923:           for(j=1; j<=(nlstate+ndeath);j++){
                   5924:             k=k+1;
                   5925:             gp[k]=pmmij[i][j];
                   5926:           }
                   5927:         }
1.220     brouard  5928:                                
1.222     brouard  5929:         for(i=1; i<=npar; i++)
                   5930:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5931:                                
1.222     brouard  5932:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5933:         k=0;
                   5934:         for(i=1; i<=(nlstate); i++){
                   5935:           for(j=1; j<=(nlstate+ndeath);j++){
                   5936:             k=k+1;
                   5937:             gm[k]=pmmij[i][j];
                   5938:           }
                   5939:         }
1.220     brouard  5940:                                
1.222     brouard  5941:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5942:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5943:        }
1.126     brouard  5944: 
1.222     brouard  5945:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5946:         for(theta=1; theta <=npar; theta++)
                   5947:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5948:                        
1.222     brouard  5949:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5950:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5951:                        
1.222     brouard  5952:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5953:                        
1.222     brouard  5954:        k=0;
                   5955:        for(i=1; i<=(nlstate); i++){
                   5956:         for(j=1; j<=(nlstate+ndeath);j++){
                   5957:           k=k+1;
                   5958:           mu[k][(int) age]=pmmij[i][j];
                   5959:         }
                   5960:        }
                   5961:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5962:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5963:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5964:                        
1.222     brouard  5965:        /*printf("\n%d ",(int)age);
                   5966:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5967:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5968:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5969:         }*/
1.220     brouard  5970:                        
1.222     brouard  5971:        fprintf(ficresprob,"\n%d ",(int)age);
                   5972:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5973:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5974:                        
1.222     brouard  5975:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5976:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5977:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5978:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5979:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5980:        }
                   5981:        i=0;
                   5982:        for (k=1; k<=(nlstate);k++){
                   5983:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5984:           i++;
                   5985:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5986:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5987:           for (j=1; j<=i;j++){
                   5988:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5989:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5990:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5991:           }
                   5992:         }
                   5993:        }/* end of loop for state */
                   5994:      } /* end of loop for age */
                   5995:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5996:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5997:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5998:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5999:     
                   6000:      /* Confidence intervalle of pij  */
                   6001:      /*
                   6002:        fprintf(ficgp,"\nunset parametric;unset label");
                   6003:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6004:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6005:        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);
                   6006:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6007:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6008:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6009:      */
                   6010:                
                   6011:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6012:      first1=1;first2=2;
                   6013:      for (k2=1; k2<=(nlstate);k2++){
                   6014:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6015:         if(l2==k2) continue;
                   6016:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6017:         for (k1=1; k1<=(nlstate);k1++){
                   6018:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6019:             if(l1==k1) continue;
                   6020:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6021:             if(i<=j) continue;
                   6022:             for (age=bage; age<=fage; age ++){ 
                   6023:               if ((int)age %5==0){
                   6024:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6025:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6026:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6027:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6028:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6029:                 c12=cv12/sqrt(v1*v2);
                   6030:                 /* Computing eigen value of matrix of covariance */
                   6031:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6032:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6033:                 if ((lc2 <0) || (lc1 <0) ){
                   6034:                   if(first2==1){
                   6035:                     first1=0;
                   6036:                     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);
                   6037:                   }
                   6038:                   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);
                   6039:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6040:                   /* lc2=fabs(lc2); */
                   6041:                 }
1.220     brouard  6042:                                                                
1.222     brouard  6043:                 /* Eigen vectors */
                   6044:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   6045:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6046:                 v21=(lc1-v1)/cv12*v11;
                   6047:                 v12=-v21;
                   6048:                 v22=v11;
                   6049:                 tnalp=v21/v11;
                   6050:                 if(first1==1){
                   6051:                   first1=0;
                   6052:                   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);
                   6053:                 }
                   6054:                 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);
                   6055:                 /*printf(fignu*/
                   6056:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6057:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6058:                 if(first==1){
                   6059:                   first=0;
                   6060:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6061:                   fprintf(ficgp,"\nset parametric;unset label");
                   6062:                   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);
                   6063:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6064:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6065:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6066: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6067:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6068:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6069:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6070:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6071:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6072:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6073:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6074:                   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",      \
                   6075:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6076:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6077:                 }else{
                   6078:                   first=0;
                   6079:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6080:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6081:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6082:                   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", \
                   6083:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6084:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6085:                 }/* if first */
                   6086:               } /* age mod 5 */
                   6087:             } /* end loop age */
                   6088:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6089:             first=1;
                   6090:           } /*l12 */
                   6091:         } /* k12 */
                   6092:        } /*l1 */
                   6093:      }/* k1 */
                   6094:    }  /* loop on combination of covariates j1 */
                   6095:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6096:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6097:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6098:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6099:    free_vector(xp,1,npar);
                   6100:    fclose(ficresprob);
                   6101:    fclose(ficresprobcov);
                   6102:    fclose(ficresprobcor);
                   6103:    fflush(ficgp);
                   6104:    fflush(fichtmcov);
                   6105:  }
1.126     brouard  6106: 
                   6107: 
                   6108: /******************* Printing html file ***********/
1.201     brouard  6109: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6110:                  int lastpass, int stepm, int weightopt, char model[],\
                   6111:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6112:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6113:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6114:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6115:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6116: 
                   6117:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6118:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6119: </ul>");
1.237     brouard  6120:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6121: </ul>", model);
1.214     brouard  6122:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6123:    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",
                   6124:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6125:    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  6126:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6127:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6128:    fprintf(fichtm,"\
                   6129:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6130:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6131:    fprintf(fichtm,"\
1.217     brouard  6132:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6133:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6134:    fprintf(fichtm,"\
1.126     brouard  6135:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6136:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6137:    fprintf(fichtm,"\
1.217     brouard  6138:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6139:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6140:    fprintf(fichtm,"\
1.211     brouard  6141:  - (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  6142:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6143:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6144:    if(prevfcast==1){
                   6145:      fprintf(fichtm,"\
                   6146:  - Prevalence projections by age and states:                           \
1.201     brouard  6147:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6148:    }
1.126     brouard  6149: 
1.222     brouard  6150:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6151: 
1.225     brouard  6152:    m=pow(2,cptcoveff);
1.222     brouard  6153:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6154: 
1.222     brouard  6155:    jj1=0;
1.237     brouard  6156: 
                   6157:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6158:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.237     brouard  6159:      if(TKresult[nres]!= k1)
                   6160:        continue;
1.220     brouard  6161: 
1.222     brouard  6162:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6163:      jj1++;
                   6164:      if (cptcovn > 0) {
                   6165:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6166:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6167:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6168:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6169:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6170:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6171:        }
1.237     brouard  6172:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6173:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6174:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6175:       }
                   6176:        
1.230     brouard  6177:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6178:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6179:        if(invalidvarcomb[k1]){
                   6180:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6181:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6182:         continue;
                   6183:        }
                   6184:      }
                   6185:      /* aij, bij */
1.241     brouard  6186:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1-%d.svg\">%s_%d-1-%d.svg</a><br> \
                   6187: <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  6188:      /* Pij */
1.241     brouard  6189:      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> \
                   6190: <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  6191:      /* Quasi-incidences */
                   6192:      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  6193:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6194:  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  6195: 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> \
                   6196: <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  6197:      /* Survival functions (period) in state j */
                   6198:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6199:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive 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> \
                   6200: <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  6201:      }
                   6202:      /* State specific survival functions (period) */
                   6203:      for(cpt=1; cpt<=nlstate;cpt++){
                   6204:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6205:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.241     brouard  6206:  <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  6207:      }
                   6208:      /* Period (stable) prevalence in each health state */
                   6209:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6210:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be 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> \
                   6211: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  6212:      }
                   6213:      if(backcast==1){
                   6214:        /* Period (stable) back prevalence in each health state */
                   6215:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6216:         fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be 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> \
                   6217: <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  6218:        }
1.217     brouard  6219:      }
1.222     brouard  6220:      if(prevfcast==1){
                   6221:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6222:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6223:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be 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> \
                   6224: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  6225:        }
                   6226:      }
1.220     brouard  6227:         
1.222     brouard  6228:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6229:        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> \
                   6230: <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  6231:      }
                   6232:      /* } /\* end i1 *\/ */
                   6233:    }/* End k1 */
                   6234:    fprintf(fichtm,"</ul>");
1.126     brouard  6235: 
1.222     brouard  6236:    fprintf(fichtm,"\
1.126     brouard  6237: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6238:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6239:  - 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  6240: But because parameters are usually highly correlated (a higher incidence of disability \
                   6241: and a higher incidence of recovery can give very close observed transition) it might \
                   6242: be very useful to look not only at linear confidence intervals estimated from the \
                   6243: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6244: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6245: covariance matrix of the one-step probabilities. \
                   6246: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6247: 
1.222     brouard  6248:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6249:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6250:    fprintf(fichtm,"\
1.126     brouard  6251:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6252:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6253: 
1.222     brouard  6254:    fprintf(fichtm,"\
1.126     brouard  6255:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6256:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6257:    fprintf(fichtm,"\
1.126     brouard  6258:  - 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): \
                   6259:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6260:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6261:    fprintf(fichtm,"\
1.126     brouard  6262:  - (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): \
                   6263:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6264:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6265:    fprintf(fichtm,"\
1.128     brouard  6266:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the 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  6267:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6268:    fprintf(fichtm,"\
1.128     brouard  6269:  - 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  6270:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6271:    fprintf(fichtm,"\
1.126     brouard  6272:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6273:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6274: 
                   6275: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6276: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6277: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6278: /*     <br>",fileres,fileres,fileres,fileres); */
                   6279: /*  else  */
                   6280: /*    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  6281:    fflush(fichtm);
                   6282:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6283: 
1.225     brouard  6284:    m=pow(2,cptcoveff);
1.222     brouard  6285:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6286: 
1.222     brouard  6287:    jj1=0;
1.237     brouard  6288: 
1.241     brouard  6289:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  6290:    for(k1=1; k1<=m;k1++){
1.237     brouard  6291:      if(TKresult[nres]!= k1)
                   6292:        continue;
1.222     brouard  6293:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6294:      jj1++;
1.126     brouard  6295:      if (cptcovn > 0) {
                   6296:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6297:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6298:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6299:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6300:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6301:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6302:       }
                   6303: 
1.126     brouard  6304:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6305: 
1.222     brouard  6306:        if(invalidvarcomb[k1]){
                   6307:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6308:         continue;
                   6309:        }
1.126     brouard  6310:      }
                   6311:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6312:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
1.241     brouard  6313: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
                   6314: <img src=\"%s_%d-%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);  
1.126     brouard  6315:      }
                   6316:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6317: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6318: true period expectancies (those weighted with period prevalences are also\
                   6319:  drawn in addition to the population based expectancies computed using\
1.241     brouard  6320:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   6321: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  6322:      /* } /\* end i1 *\/ */
                   6323:    }/* End k1 */
1.241     brouard  6324:   }/* End nres */
1.222     brouard  6325:    fprintf(fichtm,"</ul>");
                   6326:    fflush(fichtm);
1.126     brouard  6327: }
                   6328: 
                   6329: /******************* Gnuplot file **************/
1.223     brouard  6330: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6331: 
                   6332:   char dirfileres[132],optfileres[132];
1.223     brouard  6333:   char gplotcondition[132];
1.237     brouard  6334:   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  6335:   int lv=0, vlv=0, kl=0;
1.130     brouard  6336:   int ng=0;
1.201     brouard  6337:   int vpopbased;
1.223     brouard  6338:   int ioffset; /* variable offset for columns */
1.235     brouard  6339:   int nres=0; /* Index of resultline */
1.219     brouard  6340: 
1.126     brouard  6341: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6342: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6343: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6344: /*   } */
                   6345: 
                   6346:   /*#ifdef windows */
                   6347:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6348:   /*#endif */
1.225     brouard  6349:   m=pow(2,cptcoveff);
1.126     brouard  6350: 
1.202     brouard  6351:   /* Contribution to likelihood */
                   6352:   /* Plot the probability implied in the likelihood */
1.223     brouard  6353:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6354:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6355:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6356:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6357: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6358:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6359: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6360:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6361:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6362:   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));
                   6363:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6364:   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));
                   6365:   for (i=1; i<= nlstate ; i ++) {
                   6366:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6367:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6368:     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);
                   6369:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6370:       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);
                   6371:     }
                   6372:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6373:   }
                   6374:   /* 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 */               
                   6375:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6376:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6377:   fprintf(ficgp,"\nset out;unset log\n");
                   6378:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6379: 
1.126     brouard  6380:   strcpy(dirfileres,optionfilefiname);
                   6381:   strcpy(optfileres,"vpl");
1.223     brouard  6382:   /* 1eme*/
1.238     brouard  6383:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6384:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6385:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6386:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6387:        if(TKresult[nres]!= k1)
                   6388:          continue;
                   6389:        /* We are interested in selected combination by the resultline */
                   6390:        printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
                   6391:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6392:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6393:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6394:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6395:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6396:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6397:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6398:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
                   6399:          printf(" V%d=%d ",Tvaraff[k],vlv);
                   6400:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6401:        }
                   6402:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6403:          printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6404:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6405:        }       
                   6406:        printf("\n#\n");
                   6407:        fprintf(ficgp,"\n#\n");
                   6408:        if(invalidvarcomb[k1]){
                   6409:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6410:          continue;
                   6411:        }
1.235     brouard  6412:       
1.241     brouard  6413:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   6414:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   6415:        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);
1.235     brouard  6416:       
1.238     brouard  6417:        for (i=1; i<= nlstate ; i ++) {
                   6418:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6419:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6420:        }
1.242   ! brouard  6421:        fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres);
1.238     brouard  6422:        for (i=1; i<= nlstate ; i ++) {
                   6423:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6424:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6425:        } 
1.242   ! brouard  6426:        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_"),k1-1,k1-1,nres); 
1.238     brouard  6427:        for (i=1; i<= nlstate ; i ++) {
                   6428:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6429:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6430:        }  
                   6431:        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));
                   6432:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6433:          /* 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  6434:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  6435:          if(cptcoveff ==0){
                   6436:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",        2+(cpt-1),  cpt );
                   6437:          }else{
                   6438:            kl=0;
                   6439:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6440:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6441:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6442:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6443:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6444:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6445:              kl++;
1.238     brouard  6446:              /* 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 *\/ */
                   6447:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6448:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6449:              /* ''  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*/
                   6450:              if(k==cptcoveff){
                   6451:                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
1.242   ! brouard  6452:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  6453:              }else{
                   6454:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6455:                kl++;
                   6456:              }
                   6457:            } /* end covariate */
                   6458:          } /* end if no covariate */
                   6459:        } /* end if backcast */
                   6460:        fprintf(ficgp,"\nset out \n");
                   6461:       } /* nres */
1.201     brouard  6462:     } /* k1 */
                   6463:   } /* cpt */
1.235     brouard  6464: 
                   6465:   
1.126     brouard  6466:   /*2 eme*/
1.238     brouard  6467:   for (k1=1; k1<= m ; k1 ++){  
                   6468:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6469:       if(TKresult[nres]!= k1)
                   6470:        continue;
                   6471:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6472:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6473:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6474:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6475:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6476:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6477:        vlv= nbcode[Tvaraff[k]][lv];
                   6478:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6479:       }
1.237     brouard  6480:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6481:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6482:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6483:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6484:       }
1.211     brouard  6485:       fprintf(ficgp,"\n#\n");
1.223     brouard  6486:       if(invalidvarcomb[k1]){
                   6487:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6488:        continue;
                   6489:       }
1.219     brouard  6490:                        
1.241     brouard  6491:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  6492:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6493:        if(vpopbased==0)
                   6494:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6495:        else
                   6496:          fprintf(ficgp,"\nreplot ");
                   6497:        for (i=1; i<= nlstate+1 ; i ++) {
                   6498:          k=2*i;
                   6499:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
                   6500:          for (j=1; j<= nlstate+1 ; j ++) {
                   6501:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6502:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6503:          }   
                   6504:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6505:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6506:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   6507:          for (j=1; j<= nlstate+1 ; j ++) {
                   6508:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6509:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6510:          }   
                   6511:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6512:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   6513:          for (j=1; j<= nlstate+1 ; j ++) {
                   6514:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6515:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6516:          }   
                   6517:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6518:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6519:        } /* state */
                   6520:       } /* vpopbased */
                   6521:       fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   6522:     } /* end nres */
                   6523:   } /* k1 end 2 eme*/
                   6524:        
                   6525:        
                   6526:   /*3eme*/
                   6527:   for (k1=1; k1<= m ; k1 ++){
                   6528:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.240     brouard  6529:       if(TKresult[nres]!= k1)
1.238     brouard  6530:        continue;
                   6531: 
                   6532:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6533:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6534:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6535:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6536:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6537:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6538:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6539:          vlv= nbcode[Tvaraff[k]][lv];
                   6540:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6541:        }
                   6542:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6543:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6544:        }       
                   6545:        fprintf(ficgp,"\n#\n");
                   6546:        if(invalidvarcomb[k1]){
                   6547:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6548:          continue;
                   6549:        }
                   6550:                        
                   6551:        /*       k=2+nlstate*(2*cpt-2); */
                   6552:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  6553:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.238     brouard  6554:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6555: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
1.238     brouard  6556:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6557:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6558:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6559:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6560:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6561:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6562:                                
1.238     brouard  6563:        */
                   6564:        for (i=1; i< nlstate ; i ++) {
                   6565:          fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
                   6566:          /*    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  6567:                                
1.238     brouard  6568:        } 
                   6569:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6570:       }
                   6571:     } /* end nres */
                   6572:   } /* end kl 3eme */
1.126     brouard  6573:   
1.223     brouard  6574:   /* 4eme */
1.201     brouard  6575:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6576:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6577:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6578:       if(TKresult[nres]!= k1)
1.223     brouard  6579:        continue;
1.238     brouard  6580:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6581:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6582:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6583:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6584:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6585:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6586:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6587:          vlv= nbcode[Tvaraff[k]][lv];
                   6588:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6589:        }
                   6590:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6591:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6592:        }       
                   6593:        fprintf(ficgp,"\n#\n");
                   6594:        if(invalidvarcomb[k1]){
                   6595:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6596:          continue;
1.223     brouard  6597:        }
1.238     brouard  6598:       
1.241     brouard  6599:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.238     brouard  6600:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6601: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6602:        k=3;
                   6603:        for (i=1; i<= nlstate ; i ++){
                   6604:          if(i==1){
                   6605:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6606:          }else{
                   6607:            fprintf(ficgp,", '' ");
                   6608:          }
                   6609:          l=(nlstate+ndeath)*(i-1)+1;
                   6610:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6611:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6612:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6613:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6614:        } /* nlstate */
                   6615:        fprintf(ficgp,"\nset out\n");
                   6616:       } /* end cpt state*/ 
                   6617:     } /* end nres */
                   6618:   } /* end covariate k1 */  
                   6619: 
1.220     brouard  6620: /* 5eme */
1.201     brouard  6621:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6622:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6623:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6624:       if(TKresult[nres]!= k1)
1.227     brouard  6625:        continue;
1.238     brouard  6626:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6627:        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);
                   6628:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6629:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6630:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6631:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6632:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6633:          vlv= nbcode[Tvaraff[k]][lv];
                   6634:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6635:        }
                   6636:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6637:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6638:        }       
                   6639:        fprintf(ficgp,"\n#\n");
                   6640:        if(invalidvarcomb[k1]){
                   6641:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6642:          continue;
                   6643:        }
1.227     brouard  6644:       
1.241     brouard  6645:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.238     brouard  6646:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6647: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6648:        k=3;
                   6649:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6650:          if(j==1)
                   6651:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6652:          else
                   6653:            fprintf(ficgp,", '' ");
                   6654:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6655:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6656:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6657:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6658:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6659:        } /* nlstate */
                   6660:        fprintf(ficgp,", '' ");
                   6661:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6662:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6663:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6664:          if(j < nlstate)
                   6665:            fprintf(ficgp,"$%d +",k+l);
                   6666:          else
                   6667:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6668:        }
                   6669:        fprintf(ficgp,"\nset out\n");
                   6670:       } /* end cpt state*/ 
                   6671:     } /* end covariate */  
                   6672:   } /* end nres */
1.227     brouard  6673:   
1.220     brouard  6674: /* 6eme */
1.202     brouard  6675:   /* CV preval stable (period) for each covariate */
1.237     brouard  6676:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6677:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6678:     if(TKresult[nres]!= k1)
                   6679:       continue;
1.153     brouard  6680:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6681:       
1.211     brouard  6682:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6683:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6684:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6685:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6686:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6687:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6688:        vlv= nbcode[Tvaraff[k]][lv];
                   6689:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6690:       }
1.237     brouard  6691:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6692:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6693:       }        
1.211     brouard  6694:       fprintf(ficgp,"\n#\n");
1.223     brouard  6695:       if(invalidvarcomb[k1]){
1.227     brouard  6696:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6697:        continue;
1.223     brouard  6698:       }
1.227     brouard  6699:       
1.241     brouard  6700:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.126     brouard  6701:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6702: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6703:       k=3; /* Offset */
1.153     brouard  6704:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6705:        if(i==1)
                   6706:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6707:        else
                   6708:          fprintf(ficgp,", '' ");
                   6709:        l=(nlstate+ndeath)*(i-1)+1;
                   6710:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6711:        for (j=2; j<= nlstate ; j ++)
                   6712:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6713:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6714:       } /* nlstate */
1.201     brouard  6715:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6716:     } /* end cpt state*/ 
                   6717:   } /* end covariate */  
1.227     brouard  6718:   
                   6719:   
1.220     brouard  6720: /* 7eme */
1.218     brouard  6721:   if(backcast == 1){
1.217     brouard  6722:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6723:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6724:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6725:       if(TKresult[nres]!= k1)
                   6726:        continue;
1.218     brouard  6727:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6728:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6729:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6730:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6731:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6732:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6733:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6734:          vlv= nbcode[Tvaraff[k]][lv];
                   6735:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6736:        }
1.237     brouard  6737:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6738:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6739:        }       
1.227     brouard  6740:        fprintf(ficgp,"\n#\n");
                   6741:        if(invalidvarcomb[k1]){
                   6742:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6743:          continue;
                   6744:        }
                   6745:        
1.241     brouard  6746:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.227     brouard  6747:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6748: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6749:        k=3; /* Offset */
                   6750:        for (i=1; i<= nlstate ; i ++){
                   6751:          if(i==1)
                   6752:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6753:          else
                   6754:            fprintf(ficgp,", '' ");
                   6755:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6756:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6757:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6758:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6759:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6760:          /* for (j=2; j<= nlstate ; j ++) */
                   6761:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6762:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6763:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6764:        } /* nlstate */
                   6765:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6766:       } /* end cpt state*/ 
                   6767:     } /* end covariate */  
                   6768:   } /* End if backcast */
                   6769:   
1.223     brouard  6770:   /* 8eme */
1.218     brouard  6771:   if(prevfcast==1){
                   6772:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6773:     
1.237     brouard  6774:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6775:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6776:       if(TKresult[nres]!= k1)
                   6777:        continue;
1.211     brouard  6778:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6779:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6780:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6781:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6782:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6783:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6784:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6785:          vlv= nbcode[Tvaraff[k]][lv];
                   6786:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6787:        }
1.237     brouard  6788:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6789:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6790:        }       
1.227     brouard  6791:        fprintf(ficgp,"\n#\n");
                   6792:        if(invalidvarcomb[k1]){
                   6793:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6794:          continue;
                   6795:        }
                   6796:        
                   6797:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  6798:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.227     brouard  6799:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  6800: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6801:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6802:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6803:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6804:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6805:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6806:          if(i==1){
                   6807:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6808:          }else{
                   6809:            fprintf(ficgp,",\\\n '' ");
                   6810:          }
                   6811:          if(cptcoveff ==0){ /* No covariate */
                   6812:            ioffset=2; /* Age is in 2 */
                   6813:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6814:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6815:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6816:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6817:            fprintf(ficgp," u %d:(", ioffset); 
                   6818:            if(i==nlstate+1)
                   6819:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6820:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6821:            else
                   6822:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6823:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6824:          }else{ /* more than 2 covariates */
                   6825:            if(cptcoveff ==1){
                   6826:              ioffset=4; /* Age is in 4 */
                   6827:            }else{
                   6828:              ioffset=6; /* Age is in 6 */
                   6829:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6830:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6831:            }   
                   6832:            fprintf(ficgp," u %d:(",ioffset); 
                   6833:            kl=0;
                   6834:            strcpy(gplotcondition,"(");
                   6835:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6836:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6837:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6838:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6839:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6840:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6841:              kl++;
                   6842:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6843:              kl++;
                   6844:              if(k <cptcoveff && cptcoveff>1)
                   6845:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6846:            }
                   6847:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6848:            /* 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 *\/ */
                   6849:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6850:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6851:            /* ''  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*/
                   6852:            if(i==nlstate+1){
                   6853:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6854:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6855:            }else{
                   6856:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6857:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6858:            }
                   6859:          } /* end if covariate */
                   6860:        } /* nlstate */
                   6861:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6862:       } /* end cpt state*/
                   6863:     } /* end covariate */
                   6864:   } /* End if prevfcast */
1.227     brouard  6865:   
                   6866:   
1.238     brouard  6867:   /* 9eme writing MLE parameters */
                   6868:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  6869:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6870:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6871:     for(k=1; k <=(nlstate+ndeath); k++){
                   6872:       if (k != i) {
1.227     brouard  6873:        fprintf(ficgp,"#   current state %d\n",k);
                   6874:        for(j=1; j <=ncovmodel; j++){
                   6875:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6876:          jk++; 
                   6877:        }
                   6878:        fprintf(ficgp,"\n");
1.126     brouard  6879:       }
                   6880:     }
1.223     brouard  6881:   }
1.187     brouard  6882:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6883:   
1.145     brouard  6884:   /*goto avoid;*/
1.238     brouard  6885:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   6886:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6887:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6888:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6889:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6890:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6891:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6892:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6893:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6894:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6895:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6896:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6897:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6898:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6899:   fprintf(ficgp,"#\n");
1.223     brouard  6900:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  6901:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  6902:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  6903:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  6904:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   6905:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   6906:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6907:       if(TKresult[nres]!= jk)
                   6908:        continue;
                   6909:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   6910:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6911:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6912:       }        
                   6913:       fprintf(ficgp,"\n#\n");
1.241     brouard  6914:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
1.223     brouard  6915:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6916:       if (ng==1){
                   6917:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6918:        fprintf(ficgp,"\nunset log y");
                   6919:       }else if (ng==2){
                   6920:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6921:        fprintf(ficgp,"\nset log y");
                   6922:       }else if (ng==3){
                   6923:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6924:        fprintf(ficgp,"\nset log y");
                   6925:       }else
                   6926:        fprintf(ficgp,"\nunset title ");
                   6927:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6928:       i=1;
                   6929:       for(k2=1; k2<=nlstate; k2++) {
                   6930:        k3=i;
                   6931:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6932:          if (k != k2){
                   6933:            switch( ng) {
                   6934:            case 1:
                   6935:              if(nagesqr==0)
                   6936:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6937:              else /* nagesqr =1 */
                   6938:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6939:              break;
                   6940:            case 2: /* ng=2 */
                   6941:              if(nagesqr==0)
                   6942:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6943:              else /* nagesqr =1 */
                   6944:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6945:              break;
                   6946:            case 3:
                   6947:              if(nagesqr==0)
                   6948:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6949:              else /* nagesqr =1 */
                   6950:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6951:              break;
                   6952:            }
                   6953:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  6954:            ijp=1; /* product no age */
                   6955:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   6956:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  6957:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  6958:              if(j==Tage[ij]) { /* Product by age */
                   6959:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  6960:                  if(DummyV[j]==0){
1.237     brouard  6961:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   6962:                  }else{ /* quantitative */
                   6963:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   6964:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6965:                  }
                   6966:                  ij++;
                   6967:                }
                   6968:              }else if(j==Tprod[ijp]) { /* */ 
                   6969:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   6970:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  6971:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   6972:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  6973:                      /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],nbcode[Tvard[ijp][2]][codtabm(jk,j)]); */
                   6974:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   6975:                    }else{ /* Vn is dummy and Vm is quanti */
                   6976:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   6977:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6978:                    }
                   6979:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  6980:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  6981:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   6982:                    }else{ /* Both quanti */
                   6983:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6984:                    }
                   6985:                  }
1.238     brouard  6986:                  ijp++;
1.237     brouard  6987:                }
                   6988:              } else{  /* simple covariate */
                   6989:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   6990:                if(Dummy[j]==0){
                   6991:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   6992:                }else{ /* quantitative */
                   6993:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  6994:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6995:                }
1.237     brouard  6996:              } /* end simple */
                   6997:            } /* end j */
1.223     brouard  6998:          }else{
                   6999:            i=i-ncovmodel;
                   7000:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   7001:              fprintf(ficgp," (1.");
                   7002:          }
1.227     brouard  7003:          
1.223     brouard  7004:          if(ng != 1){
                   7005:            fprintf(ficgp,")/(1");
1.227     brouard  7006:            
1.223     brouard  7007:            for(k1=1; k1 <=nlstate; k1++){ 
                   7008:              if(nagesqr==0)
                   7009:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   7010:              else /* nagesqr =1 */
                   7011:                fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
1.217     brouard  7012:               
1.223     brouard  7013:              ij=1;
                   7014:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  7015:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   7016:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  7017:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   7018:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7019:                    ij++;
                   7020:                  }
                   7021:                }
                   7022:                else
1.225     brouard  7023:                  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);/* Valgrind bug nbcode */
1.223     brouard  7024:              }
                   7025:              fprintf(ficgp,")");
                   7026:            }
                   7027:            fprintf(ficgp,")");
                   7028:            if(ng ==2)
                   7029:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   7030:            else /* ng= 3 */
                   7031:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   7032:          }else{ /* end ng <> 1 */
                   7033:            if( k !=k2) /* logit p11 is hard to draw */
                   7034:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   7035:          }
                   7036:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   7037:            fprintf(ficgp,",");
                   7038:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   7039:            fprintf(ficgp,",");
                   7040:          i=i+ncovmodel;
                   7041:        } /* end k */
                   7042:       } /* end k2 */
                   7043:       fprintf(ficgp,"\n set out\n");
                   7044:     } /* end jk */
                   7045:   } /* end ng */
                   7046:   /* avoid: */
                   7047:   fflush(ficgp); 
1.126     brouard  7048: }  /* end gnuplot */
                   7049: 
                   7050: 
                   7051: /*************** Moving average **************/
1.219     brouard  7052: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  7053:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7054:    
1.222     brouard  7055:    int i, cpt, cptcod;
                   7056:    int modcovmax =1;
                   7057:    int mobilavrange, mob;
                   7058:    int iage=0;
                   7059: 
                   7060:    double sum=0.;
                   7061:    double age;
                   7062:    double *sumnewp, *sumnewm;
                   7063:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7064:   
                   7065:   
1.225     brouard  7066:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7067:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7068: 
                   7069:    sumnewp = vector(1,ncovcombmax);
                   7070:    sumnewm = vector(1,ncovcombmax);
                   7071:    agemingood = vector(1,ncovcombmax); 
                   7072:    agemaxgood = vector(1,ncovcombmax);
                   7073: 
                   7074:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7075:      sumnewm[cptcod]=0.;
                   7076:      sumnewp[cptcod]=0.;
                   7077:      agemingood[cptcod]=0;
                   7078:      agemaxgood[cptcod]=0;
                   7079:    }
                   7080:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7081:   
                   7082:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7083:      if(mobilav==1) mobilavrange=5; /* default */
                   7084:      else mobilavrange=mobilav;
                   7085:      for (age=bage; age<=fage; age++)
                   7086:        for (i=1; i<=nlstate;i++)
                   7087:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7088:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7089:      /* We keep the original values on the extreme ages bage, fage and for 
                   7090:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7091:        we use a 5 terms etc. until the borders are no more concerned. 
                   7092:      */ 
                   7093:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7094:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7095:         for (i=1; i<=nlstate;i++){
                   7096:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7097:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7098:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7099:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7100:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7101:             }
                   7102:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7103:           }
                   7104:         }
                   7105:        }/* end age */
                   7106:      }/* end mob */
                   7107:    }else
                   7108:      return -1;
                   7109:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7110:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7111:      if(invalidvarcomb[cptcod]){
                   7112:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7113:        continue;
                   7114:      }
1.219     brouard  7115: 
1.222     brouard  7116:      agemingood[cptcod]=fage-(mob-1)/2;
                   7117:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7118:        sumnewm[cptcod]=0.;
                   7119:        for (i=1; i<=nlstate;i++){
                   7120:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7121:        }
                   7122:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7123:         agemingood[cptcod]=age;
                   7124:        }else{ /* bad */
                   7125:         for (i=1; i<=nlstate;i++){
                   7126:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7127:         } /* i */
                   7128:        } /* end bad */
                   7129:      }/* age */
                   7130:      sum=0.;
                   7131:      for (i=1; i<=nlstate;i++){
                   7132:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7133:      }
                   7134:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7135:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
                   7136:        /* for (i=1; i<=nlstate;i++){ */
                   7137:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7138:        /* } /\* i *\/ */
                   7139:      } /* end bad */
                   7140:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7141:      /* From youngest, finding the oldest wrong */
                   7142:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7143:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7144:        sumnewm[cptcod]=0.;
                   7145:        for (i=1; i<=nlstate;i++){
                   7146:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7147:        }
                   7148:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7149:         agemaxgood[cptcod]=age;
                   7150:        }else{ /* bad */
                   7151:         for (i=1; i<=nlstate;i++){
                   7152:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7153:         } /* i */
                   7154:        } /* end bad */
                   7155:      }/* age */
                   7156:      sum=0.;
                   7157:      for (i=1; i<=nlstate;i++){
                   7158:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7159:      }
                   7160:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7161:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
                   7162:        /* for (i=1; i<=nlstate;i++){ */
                   7163:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7164:        /* } /\* i *\/ */
                   7165:      } /* end bad */
                   7166:                
                   7167:      for (age=bage; age<=fage; age++){
1.235     brouard  7168:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7169:        sumnewp[cptcod]=0.;
                   7170:        sumnewm[cptcod]=0.;
                   7171:        for (i=1; i<=nlstate;i++){
                   7172:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7173:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7174:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7175:        }
                   7176:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7177:      }
                   7178:      /* printf("\n"); */
                   7179:      /* } */
                   7180:      /* brutal averaging */
                   7181:      for (i=1; i<=nlstate;i++){
                   7182:        for (age=1; age<=bage; age++){
                   7183:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7184:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7185:        }       
                   7186:        for (age=fage; age<=AGESUP; age++){
                   7187:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7188:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7189:        }
                   7190:      } /* end i status */
                   7191:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7192:        for (age=1; age<=AGESUP; age++){
                   7193:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7194:         mobaverage[(int)age][i][cptcod]=0.;
                   7195:        }
                   7196:      }
                   7197:    }/* end cptcod */
                   7198:    free_vector(sumnewm,1, ncovcombmax);
                   7199:    free_vector(sumnewp,1, ncovcombmax);
                   7200:    free_vector(agemaxgood,1, ncovcombmax);
                   7201:    free_vector(agemingood,1, ncovcombmax);
                   7202:    return 0;
                   7203:  }/* End movingaverage */
1.218     brouard  7204:  
1.126     brouard  7205: 
                   7206: /************** Forecasting ******************/
1.235     brouard  7207:  void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
1.126     brouard  7208:   /* proj1, year, month, day of starting projection 
                   7209:      agemin, agemax range of age
                   7210:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7211:      anproj2 year of en of projection (same day and month as proj1).
                   7212:   */
1.235     brouard  7213:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7214:   double agec; /* generic age */
                   7215:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7216:   double *popeffectif,*popcount;
                   7217:   double ***p3mat;
1.218     brouard  7218:   /* double ***mobaverage; */
1.126     brouard  7219:   char fileresf[FILENAMELENGTH];
                   7220: 
                   7221:   agelim=AGESUP;
1.211     brouard  7222:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7223:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7224:      We still use firstpass and lastpass as another selection.
                   7225:   */
1.214     brouard  7226:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7227:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7228:  
1.201     brouard  7229:   strcpy(fileresf,"F_"); 
                   7230:   strcat(fileresf,fileresu);
1.126     brouard  7231:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7232:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7233:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7234:   }
1.235     brouard  7235:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7236:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7237: 
1.225     brouard  7238:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7239: 
                   7240: 
                   7241:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7242:   if (stepm<=12) stepsize=1;
                   7243:   if(estepm < stepm){
                   7244:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7245:   }
                   7246:   else  hstepm=estepm;   
                   7247: 
                   7248:   hstepm=hstepm/stepm; 
                   7249:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7250:                                fractional in yp1 */
                   7251:   anprojmean=yp;
                   7252:   yp2=modf((yp1*12),&yp);
                   7253:   mprojmean=yp;
                   7254:   yp1=modf((yp2*30.5),&yp);
                   7255:   jprojmean=yp;
                   7256:   if(jprojmean==0) jprojmean=1;
                   7257:   if(mprojmean==0) jprojmean=1;
                   7258: 
1.227     brouard  7259:   i1=pow(2,cptcoveff);
1.126     brouard  7260:   if (cptcovn < 1){i1=1;}
                   7261:   
                   7262:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7263:   
                   7264:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7265:   
1.126     brouard  7266: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7267:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7268:   for(k=1; k<=i1;k++){
                   7269:     if(TKresult[nres]!= k)
                   7270:       continue;
1.227     brouard  7271:     if(invalidvarcomb[k]){
                   7272:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7273:       continue;
                   7274:     }
                   7275:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7276:     for(j=1;j<=cptcoveff;j++) {
                   7277:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7278:     }
1.235     brouard  7279:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7280:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7281:     }
1.227     brouard  7282:     fprintf(ficresf," yearproj age");
                   7283:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7284:       for(i=1; i<=nlstate;i++)               
                   7285:        fprintf(ficresf," p%d%d",i,j);
                   7286:       fprintf(ficresf," wp.%d",j);
                   7287:     }
                   7288:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7289:       fprintf(ficresf,"\n");
                   7290:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7291:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7292:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7293:        nhstepm = nhstepm/hstepm; 
                   7294:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7295:        oldm=oldms;savm=savms;
1.235     brouard  7296:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7297:        
                   7298:        for (h=0; h<=nhstepm; h++){
                   7299:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7300:            fprintf(ficresf,"\n");
                   7301:            for(j=1;j<=cptcoveff;j++) 
                   7302:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7303:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7304:          } 
                   7305:          for(j=1; j<=nlstate+ndeath;j++) {
                   7306:            ppij=0.;
                   7307:            for(i=1; i<=nlstate;i++) {
                   7308:              if (mobilav==1) 
                   7309:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7310:              else {
                   7311:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7312:              }
                   7313:              if (h*hstepm/YEARM*stepm== yearp) {
                   7314:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7315:              }
                   7316:            } /* end i */
                   7317:            if (h*hstepm/YEARM*stepm==yearp) {
                   7318:              fprintf(ficresf," %.3f", ppij);
                   7319:            }
                   7320:          }/* end j */
                   7321:        } /* end h */
                   7322:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7323:       } /* end agec */
                   7324:     } /* end yearp */
                   7325:   } /* end  k */
1.219     brouard  7326:        
1.126     brouard  7327:   fclose(ficresf);
1.215     brouard  7328:   printf("End of Computing forecasting \n");
                   7329:   fprintf(ficlog,"End of Computing forecasting\n");
                   7330: 
1.126     brouard  7331: }
                   7332: 
1.218     brouard  7333: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7334: /* void prevbackforecast(char fileres[], 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){ */
1.218     brouard  7335: /*   /\* back1, year, month, day of starting backection  */
                   7336: /*      agemin, agemax range of age */
                   7337: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7338: /*      anback2 year of en of backection (same day and month as back1). */
                   7339: /*   *\/ */
                   7340: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7341: /*   double agec; /\* generic age *\/ */
                   7342: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7343: /*   double *popeffectif,*popcount; */
                   7344: /*   double ***p3mat; */
                   7345: /*   /\* double ***mobaverage; *\/ */
                   7346: /*   char fileresfb[FILENAMELENGTH]; */
                   7347:        
                   7348: /*   agelim=AGESUP; */
                   7349: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7350: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7351: /*      We still use firstpass and lastpass as another selection. */
                   7352: /*   *\/ */
                   7353: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7354: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7355: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7356:        
                   7357: /*   strcpy(fileresfb,"FB_");  */
                   7358: /*   strcat(fileresfb,fileresu); */
                   7359: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7360: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7361: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7362: /*   } */
                   7363: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7364: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7365:        
1.225     brouard  7366: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7367:        
                   7368: /*   /\* if (mobilav!=0) { *\/ */
                   7369: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7370: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7371: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7372: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7373: /*   /\*   } *\/ */
                   7374: /*   /\* } *\/ */
                   7375:        
                   7376: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7377: /*   if (stepm<=12) stepsize=1; */
                   7378: /*   if(estepm < stepm){ */
                   7379: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7380: /*   } */
                   7381: /*   else  hstepm=estepm;    */
                   7382:        
                   7383: /*   hstepm=hstepm/stepm;  */
                   7384: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7385: /*                                fractional in yp1 *\/ */
                   7386: /*   anprojmean=yp; */
                   7387: /*   yp2=modf((yp1*12),&yp); */
                   7388: /*   mprojmean=yp; */
                   7389: /*   yp1=modf((yp2*30.5),&yp); */
                   7390: /*   jprojmean=yp; */
                   7391: /*   if(jprojmean==0) jprojmean=1; */
                   7392: /*   if(mprojmean==0) jprojmean=1; */
                   7393:        
1.225     brouard  7394: /*   i1=cptcoveff; */
1.218     brouard  7395: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7396:   
1.218     brouard  7397: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7398:   
1.218     brouard  7399: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7400:        
                   7401: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7402: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7403: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7404: /*       k=k+1; */
                   7405: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7406: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7407: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7408: /*       } */
                   7409: /*       fprintf(ficresfb," yearbproj age"); */
                   7410: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7411: /*                             for(i=1; i<=nlstate;i++)               */
                   7412: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7413: /*                             fprintf(ficresfb," p.%d",j); */
                   7414: /*       } */
                   7415: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7416: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7417: /*                             fprintf(ficresfb,"\n"); */
                   7418: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7419: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7420: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7421: /*                                     nhstepm = nhstepm/hstepm;  */
                   7422: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7423: /*                                     oldm=oldms;savm=savms; */
                   7424: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7425: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7426: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7427: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7428: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7429: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7430: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7431: /*                                             }  */
                   7432: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7433: /*                                                     ppij=0.; */
                   7434: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7435: /*                                                             if (mobilav==1)  */
                   7436: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7437: /*                                                             else { */
                   7438: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7439: /*                                                             } */
                   7440: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7441: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7442: /*                                                             } */
                   7443: /*                                                     } /\* end i *\/ */
                   7444: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7445: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7446: /*                                                     } */
                   7447: /*                                             }/\* end j *\/ */
                   7448: /*                                     } /\* end h *\/ */
                   7449: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7450: /*                             } /\* end agec *\/ */
                   7451: /*       } /\* end yearp *\/ */
                   7452: /*     } /\* end cptcod *\/ */
                   7453: /*   } /\* end  cptcov *\/ */
                   7454:        
                   7455: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7456:        
                   7457: /*   fclose(ficresfb); */
                   7458: /*   printf("End of Computing Back forecasting \n"); */
                   7459: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7460:        
1.218     brouard  7461: /* } */
1.217     brouard  7462: 
1.126     brouard  7463: /************** Forecasting *****not tested NB*************/
1.227     brouard  7464: /* 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  7465:   
1.227     brouard  7466: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7467: /*   int *popage; */
                   7468: /*   double calagedatem, agelim, kk1, kk2; */
                   7469: /*   double *popeffectif,*popcount; */
                   7470: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7471: /*   /\* double ***mobaverage; *\/ */
                   7472: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7473: 
1.227     brouard  7474: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7475: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7476: /*   agelim=AGESUP; */
                   7477: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7478:   
1.227     brouard  7479: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7480:   
                   7481:   
1.227     brouard  7482: /*   strcpy(filerespop,"POP_");  */
                   7483: /*   strcat(filerespop,fileresu); */
                   7484: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7485: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7486: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7487: /*   } */
                   7488: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7489: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7490: 
1.227     brouard  7491: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7492: 
1.227     brouard  7493: /*   /\* if (mobilav!=0) { *\/ */
                   7494: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7495: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7496: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7497: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7498: /*   /\*   } *\/ */
                   7499: /*   /\* } *\/ */
1.126     brouard  7500: 
1.227     brouard  7501: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7502: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7503:   
1.227     brouard  7504: /*   agelim=AGESUP; */
1.126     brouard  7505:   
1.227     brouard  7506: /*   hstepm=1; */
                   7507: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7508:        
1.227     brouard  7509: /*   if (popforecast==1) { */
                   7510: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7511: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7512: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7513: /*     }  */
                   7514: /*     popage=ivector(0,AGESUP); */
                   7515: /*     popeffectif=vector(0,AGESUP); */
                   7516: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7517:     
1.227     brouard  7518: /*     i=1;    */
                   7519: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7520:     
1.227     brouard  7521: /*     imx=i; */
                   7522: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7523: /*   } */
1.218     brouard  7524:   
1.227     brouard  7525: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7526: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7527: /*       k=k+1; */
                   7528: /*       fprintf(ficrespop,"\n#******"); */
                   7529: /*       for(j=1;j<=cptcoveff;j++) { */
                   7530: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7531: /*       } */
                   7532: /*       fprintf(ficrespop,"******\n"); */
                   7533: /*       fprintf(ficrespop,"# Age"); */
                   7534: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7535: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7536:       
1.227     brouard  7537: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7538: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7539:        
1.227     brouard  7540: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7541: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7542: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7543:          
1.227     brouard  7544: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7545: /*       oldm=oldms;savm=savms; */
                   7546: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7547:          
1.227     brouard  7548: /*       for (h=0; h<=nhstepm; h++){ */
                   7549: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7550: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7551: /*         }  */
                   7552: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7553: /*           kk1=0.;kk2=0; */
                   7554: /*           for(i=1; i<=nlstate;i++) {               */
                   7555: /*             if (mobilav==1)  */
                   7556: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7557: /*             else { */
                   7558: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7559: /*             } */
                   7560: /*           } */
                   7561: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7562: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7563: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7564: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7565: /*           } */
                   7566: /*         } */
                   7567: /*         for(i=1; i<=nlstate;i++){ */
                   7568: /*           kk1=0.; */
                   7569: /*           for(j=1; j<=nlstate;j++){ */
                   7570: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7571: /*           } */
                   7572: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7573: /*         } */
1.218     brouard  7574:            
1.227     brouard  7575: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7576: /*           for(j=1; j<=nlstate;j++)  */
                   7577: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7578: /*       } */
                   7579: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7580: /*     } */
                   7581: /*       } */
1.218     brouard  7582:       
1.227     brouard  7583: /*       /\******\/ */
1.218     brouard  7584:       
1.227     brouard  7585: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7586: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7587: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7588: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7589: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7590:          
1.227     brouard  7591: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7592: /*       oldm=oldms;savm=savms; */
                   7593: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7594: /*       for (h=0; h<=nhstepm; h++){ */
                   7595: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7596: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7597: /*         }  */
                   7598: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7599: /*           kk1=0.;kk2=0; */
                   7600: /*           for(i=1; i<=nlstate;i++) {               */
                   7601: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7602: /*           } */
                   7603: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7604: /*         } */
                   7605: /*       } */
                   7606: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7607: /*     } */
                   7608: /*       } */
                   7609: /*     }  */
                   7610: /*   } */
1.218     brouard  7611:   
1.227     brouard  7612: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7613:   
1.227     brouard  7614: /*   if (popforecast==1) { */
                   7615: /*     free_ivector(popage,0,AGESUP); */
                   7616: /*     free_vector(popeffectif,0,AGESUP); */
                   7617: /*     free_vector(popcount,0,AGESUP); */
                   7618: /*   } */
                   7619: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7620: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7621: /*   fclose(ficrespop); */
                   7622: /* } /\* End of popforecast *\/ */
1.218     brouard  7623:  
1.126     brouard  7624: int fileappend(FILE *fichier, char *optionfich)
                   7625: {
                   7626:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7627:     printf("Problem with file: %s\n", optionfich);
                   7628:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7629:     return (0);
                   7630:   }
                   7631:   fflush(fichier);
                   7632:   return (1);
                   7633: }
                   7634: 
                   7635: 
                   7636: /**************** function prwizard **********************/
                   7637: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7638: {
                   7639: 
                   7640:   /* Wizard to print covariance matrix template */
                   7641: 
1.164     brouard  7642:   char ca[32], cb[32];
                   7643:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7644:   int numlinepar;
                   7645: 
                   7646:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7647:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7648:   for(i=1; i <=nlstate; i++){
                   7649:     jj=0;
                   7650:     for(j=1; j <=nlstate+ndeath; j++){
                   7651:       if(j==i) continue;
                   7652:       jj++;
                   7653:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7654:       printf("%1d%1d",i,j);
                   7655:       fprintf(ficparo,"%1d%1d",i,j);
                   7656:       for(k=1; k<=ncovmodel;k++){
                   7657:        /*        printf(" %lf",param[i][j][k]); */
                   7658:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7659:        printf(" 0.");
                   7660:        fprintf(ficparo," 0.");
                   7661:       }
                   7662:       printf("\n");
                   7663:       fprintf(ficparo,"\n");
                   7664:     }
                   7665:   }
                   7666:   printf("# Scales (for hessian or gradient estimation)\n");
                   7667:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7668:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7669:   for(i=1; i <=nlstate; i++){
                   7670:     jj=0;
                   7671:     for(j=1; j <=nlstate+ndeath; j++){
                   7672:       if(j==i) continue;
                   7673:       jj++;
                   7674:       fprintf(ficparo,"%1d%1d",i,j);
                   7675:       printf("%1d%1d",i,j);
                   7676:       fflush(stdout);
                   7677:       for(k=1; k<=ncovmodel;k++){
                   7678:        /*      printf(" %le",delti3[i][j][k]); */
                   7679:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7680:        printf(" 0.");
                   7681:        fprintf(ficparo," 0.");
                   7682:       }
                   7683:       numlinepar++;
                   7684:       printf("\n");
                   7685:       fprintf(ficparo,"\n");
                   7686:     }
                   7687:   }
                   7688:   printf("# Covariance matrix\n");
                   7689: /* # 121 Var(a12)\n\ */
                   7690: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7691: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7692: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7693: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7694: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7695: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7696: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7697:   fflush(stdout);
                   7698:   fprintf(ficparo,"# Covariance matrix\n");
                   7699:   /* # 121 Var(a12)\n\ */
                   7700:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7701:   /* #   ...\n\ */
                   7702:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7703:   
                   7704:   for(itimes=1;itimes<=2;itimes++){
                   7705:     jj=0;
                   7706:     for(i=1; i <=nlstate; i++){
                   7707:       for(j=1; j <=nlstate+ndeath; j++){
                   7708:        if(j==i) continue;
                   7709:        for(k=1; k<=ncovmodel;k++){
                   7710:          jj++;
                   7711:          ca[0]= k+'a'-1;ca[1]='\0';
                   7712:          if(itimes==1){
                   7713:            printf("#%1d%1d%d",i,j,k);
                   7714:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7715:          }else{
                   7716:            printf("%1d%1d%d",i,j,k);
                   7717:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7718:            /*  printf(" %.5le",matcov[i][j]); */
                   7719:          }
                   7720:          ll=0;
                   7721:          for(li=1;li <=nlstate; li++){
                   7722:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7723:              if(lj==li) continue;
                   7724:              for(lk=1;lk<=ncovmodel;lk++){
                   7725:                ll++;
                   7726:                if(ll<=jj){
                   7727:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7728:                  if(ll<jj){
                   7729:                    if(itimes==1){
                   7730:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7731:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7732:                    }else{
                   7733:                      printf(" 0.");
                   7734:                      fprintf(ficparo," 0.");
                   7735:                    }
                   7736:                  }else{
                   7737:                    if(itimes==1){
                   7738:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7739:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7740:                    }else{
                   7741:                      printf(" 0.");
                   7742:                      fprintf(ficparo," 0.");
                   7743:                    }
                   7744:                  }
                   7745:                }
                   7746:              } /* end lk */
                   7747:            } /* end lj */
                   7748:          } /* end li */
                   7749:          printf("\n");
                   7750:          fprintf(ficparo,"\n");
                   7751:          numlinepar++;
                   7752:        } /* end k*/
                   7753:       } /*end j */
                   7754:     } /* end i */
                   7755:   } /* end itimes */
                   7756: 
                   7757: } /* end of prwizard */
                   7758: /******************* Gompertz Likelihood ******************************/
                   7759: double gompertz(double x[])
                   7760: { 
                   7761:   double A,B,L=0.0,sump=0.,num=0.;
                   7762:   int i,n=0; /* n is the size of the sample */
                   7763: 
1.220     brouard  7764:   for (i=1;i<=imx ; i++) {
1.126     brouard  7765:     sump=sump+weight[i];
                   7766:     /*    sump=sump+1;*/
                   7767:     num=num+1;
                   7768:   }
                   7769:  
                   7770:  
                   7771:   /* for (i=0; i<=imx; i++) 
                   7772:      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]);*/
                   7773: 
                   7774:   for (i=1;i<=imx ; i++)
                   7775:     {
                   7776:       if (cens[i] == 1 && wav[i]>1)
                   7777:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7778:       
                   7779:       if (cens[i] == 0 && wav[i]>1)
                   7780:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7781:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7782:       
                   7783:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7784:       if (wav[i] > 1 ) { /* ??? */
                   7785:        L=L+A*weight[i];
                   7786:        /*      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]);*/
                   7787:       }
                   7788:     }
                   7789: 
                   7790:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7791:  
                   7792:   return -2*L*num/sump;
                   7793: }
                   7794: 
1.136     brouard  7795: #ifdef GSL
                   7796: /******************* Gompertz_f Likelihood ******************************/
                   7797: double gompertz_f(const gsl_vector *v, void *params)
                   7798: { 
                   7799:   double A,B,LL=0.0,sump=0.,num=0.;
                   7800:   double *x= (double *) v->data;
                   7801:   int i,n=0; /* n is the size of the sample */
                   7802: 
                   7803:   for (i=0;i<=imx-1 ; i++) {
                   7804:     sump=sump+weight[i];
                   7805:     /*    sump=sump+1;*/
                   7806:     num=num+1;
                   7807:   }
                   7808:  
                   7809:  
                   7810:   /* for (i=0; i<=imx; i++) 
                   7811:      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]);*/
                   7812:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7813:   for (i=1;i<=imx ; i++)
                   7814:     {
                   7815:       if (cens[i] == 1 && wav[i]>1)
                   7816:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7817:       
                   7818:       if (cens[i] == 0 && wav[i]>1)
                   7819:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7820:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7821:       
                   7822:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7823:       if (wav[i] > 1 ) { /* ??? */
                   7824:        LL=LL+A*weight[i];
                   7825:        /*      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]);*/
                   7826:       }
                   7827:     }
                   7828: 
                   7829:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7830:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7831:  
                   7832:   return -2*LL*num/sump;
                   7833: }
                   7834: #endif
                   7835: 
1.126     brouard  7836: /******************* Printing html file ***********/
1.201     brouard  7837: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7838:                  int lastpass, int stepm, int weightopt, char model[],\
                   7839:                  int imx,  double p[],double **matcov,double agemortsup){
                   7840:   int i,k;
                   7841: 
                   7842:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7843:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7844:   for (i=1;i<=2;i++) 
                   7845:     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  7846:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7847:   fprintf(fichtm,"</ul>");
                   7848: 
                   7849: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7850: 
                   7851:  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>");
                   7852: 
                   7853:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7854:    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]);
                   7855: 
                   7856:  
                   7857:   fflush(fichtm);
                   7858: }
                   7859: 
                   7860: /******************* Gnuplot file **************/
1.201     brouard  7861: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7862: 
                   7863:   char dirfileres[132],optfileres[132];
1.164     brouard  7864: 
1.126     brouard  7865:   int ng;
                   7866: 
                   7867: 
                   7868:   /*#ifdef windows */
                   7869:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7870:     /*#endif */
                   7871: 
                   7872: 
                   7873:   strcpy(dirfileres,optionfilefiname);
                   7874:   strcpy(optfileres,"vpl");
1.199     brouard  7875:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7876:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7877:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7878:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7879:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7880: 
                   7881: } 
                   7882: 
1.136     brouard  7883: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7884: {
1.126     brouard  7885: 
1.136     brouard  7886:   /*-------- data file ----------*/
                   7887:   FILE *fic;
                   7888:   char dummy[]="                         ";
1.240     brouard  7889:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  7890:   int lstra;
1.136     brouard  7891:   int linei, month, year,iout;
                   7892:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7893:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7894:   char *stratrunc;
1.223     brouard  7895: 
1.240     brouard  7896:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   7897:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  7898: 
1.240     brouard  7899:   for(v=1; v <=ncovcol;v++){
                   7900:     DummyV[v]=0;
                   7901:     FixedV[v]=0;
                   7902:   }
                   7903:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   7904:     DummyV[v]=1;
                   7905:     FixedV[v]=0;
                   7906:   }
                   7907:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   7908:     DummyV[v]=0;
                   7909:     FixedV[v]=1;
                   7910:   }
                   7911:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7912:     DummyV[v]=1;
                   7913:     FixedV[v]=1;
                   7914:   }
                   7915:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7916:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   7917:     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]);
                   7918:   }
1.126     brouard  7919: 
1.136     brouard  7920:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7921:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7922:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7923:   }
1.126     brouard  7924: 
1.136     brouard  7925:   i=1;
                   7926:   linei=0;
                   7927:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7928:     linei=linei+1;
                   7929:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7930:       if(line[j] == '\t')
                   7931:        line[j] = ' ';
                   7932:     }
                   7933:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7934:       ;
                   7935:     };
                   7936:     line[j+1]=0;  /* Trims blanks at end of line */
                   7937:     if(line[0]=='#'){
                   7938:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7939:       printf("Comment line\n%s\n",line);
                   7940:       continue;
                   7941:     }
                   7942:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7943:     strcpy(line, linetmp);
1.223     brouard  7944:     
                   7945:     /* Loops on waves */
                   7946:     for (j=maxwav;j>=1;j--){
                   7947:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  7948:        cutv(stra, strb, line, ' '); 
                   7949:        if(strb[0]=='.') { /* Missing value */
                   7950:          lval=-1;
                   7951:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   7952:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   7953:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   7954:            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);
                   7955:            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);
                   7956:            return 1;
                   7957:          }
                   7958:        }else{
                   7959:          errno=0;
                   7960:          /* what_kind_of_number(strb); */
                   7961:          dval=strtod(strb,&endptr); 
                   7962:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   7963:          /* if(strb != endptr && *endptr == '\0') */
                   7964:          /*    dval=dlval; */
                   7965:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7966:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7967:            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);
                   7968:            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);
                   7969:            return 1;
                   7970:          }
                   7971:          cotqvar[j][iv][i]=dval; 
                   7972:          cotvar[j][ntv+iv][i]=dval; 
                   7973:        }
                   7974:        strcpy(line,stra);
1.223     brouard  7975:       }/* end loop ntqv */
1.225     brouard  7976:       
1.223     brouard  7977:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  7978:        cutv(stra, strb, line, ' '); 
                   7979:        if(strb[0]=='.') { /* Missing value */
                   7980:          lval=-1;
                   7981:        }else{
                   7982:          errno=0;
                   7983:          lval=strtol(strb,&endptr,10); 
                   7984:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7985:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7986:            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);
                   7987:            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);
                   7988:            return 1;
                   7989:          }
                   7990:        }
                   7991:        if(lval <-1 || lval >1){
                   7992:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7993:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7994:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  7995:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   7996:  build V1=0 V2=0 for the reference value (1),\n                                \
                   7997:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  7998:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  7999:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8000:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  8001:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8002:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8003:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8004:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8005:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8006:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8007:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8008:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8009:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  8010:          return 1;
                   8011:        }
                   8012:        cotvar[j][iv][i]=(double)(lval);
                   8013:        strcpy(line,stra);
1.223     brouard  8014:       }/* end loop ntv */
1.225     brouard  8015:       
1.223     brouard  8016:       /* Statuses  at wave */
1.137     brouard  8017:       cutv(stra, strb, line, ' '); 
1.223     brouard  8018:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  8019:        lval=-1;
1.136     brouard  8020:       }else{
1.238     brouard  8021:        errno=0;
                   8022:        lval=strtol(strb,&endptr,10); 
                   8023:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8024:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8025:          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);
                   8026:          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);
                   8027:          return 1;
                   8028:        }
1.136     brouard  8029:       }
1.225     brouard  8030:       
1.136     brouard  8031:       s[j][i]=lval;
1.225     brouard  8032:       
1.223     brouard  8033:       /* Date of Interview */
1.136     brouard  8034:       strcpy(line,stra);
                   8035:       cutv(stra, strb,line,' ');
1.169     brouard  8036:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8037:       }
1.169     brouard  8038:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  8039:        month=99;
                   8040:        year=9999;
1.136     brouard  8041:       }else{
1.225     brouard  8042:        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);
                   8043:        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);
                   8044:        return 1;
1.136     brouard  8045:       }
                   8046:       anint[j][i]= (double) year; 
                   8047:       mint[j][i]= (double)month; 
                   8048:       strcpy(line,stra);
1.223     brouard  8049:     } /* End loop on waves */
1.225     brouard  8050:     
1.223     brouard  8051:     /* Date of death */
1.136     brouard  8052:     cutv(stra, strb,line,' '); 
1.169     brouard  8053:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8054:     }
1.169     brouard  8055:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8056:       month=99;
                   8057:       year=9999;
                   8058:     }else{
1.141     brouard  8059:       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  8060:       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);
                   8061:       return 1;
1.136     brouard  8062:     }
                   8063:     andc[i]=(double) year; 
                   8064:     moisdc[i]=(double) month; 
                   8065:     strcpy(line,stra);
                   8066:     
1.223     brouard  8067:     /* Date of birth */
1.136     brouard  8068:     cutv(stra, strb,line,' '); 
1.169     brouard  8069:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8070:     }
1.169     brouard  8071:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8072:       month=99;
                   8073:       year=9999;
                   8074:     }else{
1.141     brouard  8075:       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);
                   8076:       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  8077:       return 1;
1.136     brouard  8078:     }
                   8079:     if (year==9999) {
1.141     brouard  8080:       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);
                   8081:       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  8082:       return 1;
                   8083:       
1.136     brouard  8084:     }
                   8085:     annais[i]=(double)(year);
                   8086:     moisnais[i]=(double)(month); 
                   8087:     strcpy(line,stra);
1.225     brouard  8088:     
1.223     brouard  8089:     /* Sample weight */
1.136     brouard  8090:     cutv(stra, strb,line,' '); 
                   8091:     errno=0;
                   8092:     dval=strtod(strb,&endptr); 
                   8093:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8094:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8095:       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  8096:       fflush(ficlog);
                   8097:       return 1;
                   8098:     }
                   8099:     weight[i]=dval; 
                   8100:     strcpy(line,stra);
1.225     brouard  8101:     
1.223     brouard  8102:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8103:       cutv(stra, strb, line, ' '); 
                   8104:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8105:        lval=-1;
1.223     brouard  8106:       }else{
1.225     brouard  8107:        errno=0;
                   8108:        /* what_kind_of_number(strb); */
                   8109:        dval=strtod(strb,&endptr);
                   8110:        /* if(strb != endptr && *endptr == '\0') */
                   8111:        /*   dval=dlval; */
                   8112:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8113:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8114:          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);
                   8115:          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);
                   8116:          return 1;
                   8117:        }
                   8118:        coqvar[iv][i]=dval; 
1.226     brouard  8119:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8120:       }
                   8121:       strcpy(line,stra);
                   8122:     }/* end loop nqv */
1.136     brouard  8123:     
1.223     brouard  8124:     /* Covariate values */
1.136     brouard  8125:     for (j=ncovcol;j>=1;j--){
                   8126:       cutv(stra, strb,line,' '); 
1.223     brouard  8127:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8128:        lval=-1;
1.136     brouard  8129:       }else{
1.225     brouard  8130:        errno=0;
                   8131:        lval=strtol(strb,&endptr,10); 
                   8132:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8133:          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);
                   8134:          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);
                   8135:          return 1;
                   8136:        }
1.136     brouard  8137:       }
                   8138:       if(lval <-1 || lval >1){
1.225     brouard  8139:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8140:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8141:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8142:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8143:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8144:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8145:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8146:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8147:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8148:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8149:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8150:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8151:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8152:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8153:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8154:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8155:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8156:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8157:        return 1;
1.136     brouard  8158:       }
                   8159:       covar[j][i]=(double)(lval);
                   8160:       strcpy(line,stra);
                   8161:     }  
                   8162:     lstra=strlen(stra);
1.225     brouard  8163:     
1.136     brouard  8164:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8165:       stratrunc = &(stra[lstra-9]);
                   8166:       num[i]=atol(stratrunc);
                   8167:     }
                   8168:     else
                   8169:       num[i]=atol(stra);
                   8170:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8171:       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;}*/
                   8172:     
                   8173:     i=i+1;
                   8174:   } /* End loop reading  data */
1.225     brouard  8175:   
1.136     brouard  8176:   *imax=i-1; /* Number of individuals */
                   8177:   fclose(fic);
1.225     brouard  8178:   
1.136     brouard  8179:   return (0);
1.164     brouard  8180:   /* endread: */
1.225     brouard  8181:   printf("Exiting readdata: ");
                   8182:   fclose(fic);
                   8183:   return (1);
1.223     brouard  8184: }
1.126     brouard  8185: 
1.234     brouard  8186: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8187:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8188:   while (*p2 == ' ')
1.234     brouard  8189:     p2++; 
                   8190:   /* while ((*p1++ = *p2++) !=0) */
                   8191:   /*   ; */
                   8192:   /* do */
                   8193:   /*   while (*p2 == ' ') */
                   8194:   /*     p2++; */
                   8195:   /* while (*p1++ == *p2++); */
                   8196:   *stri=p2; 
1.145     brouard  8197: }
                   8198: 
1.235     brouard  8199: int decoderesult ( char resultline[], int nres)
1.230     brouard  8200: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8201: {
1.235     brouard  8202:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8203:   char resultsav[MAXLINE];
1.234     brouard  8204:   int resultmodel[MAXLINE];
                   8205:   int modelresult[MAXLINE];
1.230     brouard  8206:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8207: 
1.234     brouard  8208:   removefirstspace(&resultline);
1.233     brouard  8209:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8210: 
                   8211:   if (strstr(resultline,"v") !=0){
                   8212:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8213:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8214:     return 1;
                   8215:   }
                   8216:   trimbb(resultsav, resultline);
                   8217:   if (strlen(resultsav) >1){
                   8218:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8219:   }
1.234     brouard  8220:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8221:     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);
                   8222:     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);
                   8223:   }
                   8224:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8225:     if(nbocc(resultsav,'=') >1){
                   8226:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8227:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8228:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8229:     }else
                   8230:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8231:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8232:     
1.230     brouard  8233:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8234:     Tvarsel[k]=atoi(strc);
                   8235:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8236:     /* cptcovsel++;     */
                   8237:     if (nbocc(stra,'=') >0)
                   8238:       strcpy(resultsav,stra); /* and analyzes it */
                   8239:   }
1.235     brouard  8240:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8241:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8242:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8243:       match=0;
1.236     brouard  8244:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8245:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8246:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8247:          match=1;
                   8248:          break;
                   8249:        }
                   8250:       }
                   8251:       if(match == 0){
                   8252:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8253:       }
                   8254:     }
                   8255:   }
1.235     brouard  8256:   /* Checking for missing or useless values in comparison of current model needs */
                   8257:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8258:     match=0;
1.235     brouard  8259:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8260:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8261:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8262:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8263:          ++match;
                   8264:        }
                   8265:       }
                   8266:     }
                   8267:     if(match == 0){
                   8268:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8269:     }else if(match > 1){
                   8270:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8271:     }
                   8272:   }
1.235     brouard  8273:       
1.234     brouard  8274:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8275:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8276:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8277:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8278:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8279:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8280:   /*    1 0 0 0 */
                   8281:   /*    2 1 0 0 */
                   8282:   /*    3 0 1 0 */ 
                   8283:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8284:   /*    5 0 0 1 */
                   8285:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8286:   /*    7 0 1 1 */
                   8287:   /*    8 1 1 1 */
1.237     brouard  8288:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8289:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8290:   /* V5*age V5 known which value for nres?  */
                   8291:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8292:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8293:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8294:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8295:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8296:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8297:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8298:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8299:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8300:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8301:       k4++;;
                   8302:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8303:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8304:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8305:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8306:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8307:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8308:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8309:       k4q++;;
                   8310:     }
                   8311:   }
1.234     brouard  8312:   
1.235     brouard  8313:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8314:   return (0);
                   8315: }
1.235     brouard  8316: 
1.230     brouard  8317: int decodemodel( char model[], int lastobs)
                   8318:  /**< This routine decodes the model and returns:
1.224     brouard  8319:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8320:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8321:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8322:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8323:        * - cptcovage number of covariates with age*products =2
                   8324:        * - cptcovs number of simple covariates
                   8325:        * - 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
                   8326:        *     which is a new column after the 9 (ncovcol) variables. 
                   8327:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8328:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8329:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8330:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8331:        */
1.136     brouard  8332: {
1.238     brouard  8333:   int i, j, k, ks, v;
1.227     brouard  8334:   int  j1, k1, k2, k3, k4;
1.136     brouard  8335:   char modelsav[80];
1.145     brouard  8336:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8337:   char *strpt;
1.136     brouard  8338: 
1.145     brouard  8339:   /*removespace(model);*/
1.136     brouard  8340:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8341:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8342:     if (strstr(model,"AGE") !=0){
1.192     brouard  8343:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8344:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8345:       return 1;
                   8346:     }
1.141     brouard  8347:     if (strstr(model,"v") !=0){
                   8348:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8349:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8350:       return 1;
                   8351:     }
1.187     brouard  8352:     strcpy(modelsav,model); 
                   8353:     if ((strpt=strstr(model,"age*age")) !=0){
                   8354:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8355:       if(strpt != model){
1.234     brouard  8356:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8357:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8358:  corresponding column of parameters.\n",model);
1.234     brouard  8359:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8360:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8361:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8362:        return 1;
1.225     brouard  8363:       }
1.187     brouard  8364:       nagesqr=1;
                   8365:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8366:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8367:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8368:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8369:       else 
1.234     brouard  8370:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8371:     }else
                   8372:       nagesqr=0;
                   8373:     if (strlen(modelsav) >1){
                   8374:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8375:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8376:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8377:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8378:                     * cst, age and age*age 
                   8379:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8380:       /* including age products which are counted in cptcovage.
                   8381:        * but the covariates which are products must be treated 
                   8382:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8383:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8384:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8385:       
                   8386:       
1.187     brouard  8387:       /*   Design
                   8388:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8389:        *  <          ncovcol=8                >
                   8390:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8391:        *   k=  1    2      3       4     5       6      7        8
                   8392:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8393:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8394:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8395:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8396:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8397:        *  Tage[++cptcovage]=k
                   8398:        *       if products, new covar are created after ncovcol with k1
                   8399:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8400:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8401:        *  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
                   8402:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8403:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8404:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8405:        *  <          ncovcol=8                >
                   8406:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8407:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8408:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8409:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8410:        * p Tprod[1]@2={                         6, 5}
                   8411:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8412:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8413:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8414:        *How to reorganize?
                   8415:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8416:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8417:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8418:        * Struct []
                   8419:        */
1.225     brouard  8420:       
1.187     brouard  8421:       /* This loop fills the array Tvar from the string 'model'.*/
                   8422:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8423:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8424:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8425:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8426:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8427:       /*       k=1 Tvar[1]=2 (from V2) */
                   8428:       /*       k=5 Tvar[5] */
                   8429:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8430:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8431:       /*       } */
1.198     brouard  8432:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8433:       /*
                   8434:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8435:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8436:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8437:       }
1.187     brouard  8438:       cptcovage=0;
                   8439:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8440:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8441:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8442:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8443:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8444:        /*scanf("%d",i);*/
                   8445:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8446:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8447:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8448:            /* covar is not filled and then is empty */
                   8449:            cptcovprod--;
                   8450:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8451:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8452:            Typevar[k]=1;  /* 1 for age product */
                   8453:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8454:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8455:            /*printf("stre=%s ", stre);*/
                   8456:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8457:            cptcovprod--;
                   8458:            cutl(stre,strb,strc,'V');
                   8459:            Tvar[k]=atoi(stre);
                   8460:            Typevar[k]=1;  /* 1 for age product */
                   8461:            cptcovage++;
                   8462:            Tage[cptcovage]=k;
                   8463:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8464:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8465:            cptcovn++;
                   8466:            cptcovprodnoage++;k1++;
                   8467:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8468:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8469:                                                because this model-covariate is a construction we invent a new column
                   8470:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8471:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8472:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8473:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8474:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8475:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8476:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8477:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8478:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8479:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8480:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8481:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8482:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8483:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8484:            for (i=1; i<=lastobs;i++){
                   8485:              /* Computes the new covariate which is a product of
                   8486:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8487:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8488:            }
                   8489:          } /* End age is not in the model */
                   8490:        } /* End if model includes a product */
                   8491:        else { /* no more sum */
                   8492:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8493:          /*  scanf("%d",i);*/
                   8494:          cutl(strd,strc,strb,'V');
                   8495:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8496:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8497:          Tvar[k]=atoi(strd);
                   8498:          Typevar[k]=0;  /* 0 for simple covariates */
                   8499:        }
                   8500:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8501:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8502:                                  scanf("%d",i);*/
1.187     brouard  8503:       } /* end of loop + on total covariates */
                   8504:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8505:   } /* end if strlen(model == 0) */
1.136     brouard  8506:   
                   8507:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8508:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8509:   
1.136     brouard  8510:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8511:      printf("cptcovprod=%d ", cptcovprod);
                   8512:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8513:      scanf("%d ",i);*/
                   8514: 
                   8515: 
1.230     brouard  8516: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8517:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8518: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8519:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8520:    k =           1    2   3     4       5       6      7      8        9
                   8521:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8522:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8523:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8524:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8525:          Tmodelind[combination of covar]=k;
1.225     brouard  8526: */  
                   8527: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8528:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8529:   /* 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  8530:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8531:   printf("Model=%s\n\
                   8532: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8533: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8534: 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);
                   8535:   fprintf(ficlog,"Model=%s\n\
                   8536: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8537: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8538: 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.240     brouard  8539:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8540:   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 */
                   8541:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8542:       Fixed[k]= 0;
                   8543:       Dummy[k]= 0;
1.225     brouard  8544:       ncoveff++;
1.232     brouard  8545:       ncovf++;
1.234     brouard  8546:       nsd++;
                   8547:       modell[k].maintype= FTYPE;
                   8548:       TvarsD[nsd]=Tvar[k];
                   8549:       TvarsDind[nsd]=k;
                   8550:       TvarF[ncovf]=Tvar[k];
                   8551:       TvarFind[ncovf]=k;
                   8552:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8553:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8554:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8555:       Fixed[k]= 0;
                   8556:       Dummy[k]= 0;
                   8557:       ncoveff++;
                   8558:       ncovf++;
                   8559:       modell[k].maintype= FTYPE;
                   8560:       TvarF[ncovf]=Tvar[k];
                   8561:       TvarFind[ncovf]=k;
1.230     brouard  8562:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8563:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  8564:     }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  8565:       Fixed[k]= 0;
                   8566:       Dummy[k]= 1;
1.230     brouard  8567:       nqfveff++;
1.234     brouard  8568:       modell[k].maintype= FTYPE;
                   8569:       modell[k].subtype= FQ;
                   8570:       nsq++;
                   8571:       TvarsQ[nsq]=Tvar[k];
                   8572:       TvarsQind[nsq]=k;
1.232     brouard  8573:       ncovf++;
1.234     brouard  8574:       TvarF[ncovf]=Tvar[k];
                   8575:       TvarFind[ncovf]=k;
1.231     brouard  8576:       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  8577:       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  8578:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  8579:       Fixed[k]= 1;
                   8580:       Dummy[k]= 0;
1.225     brouard  8581:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8582:       modell[k].maintype= VTYPE;
                   8583:       modell[k].subtype= VD;
                   8584:       nsd++;
                   8585:       TvarsD[nsd]=Tvar[k];
                   8586:       TvarsDind[nsd]=k;
                   8587:       ncovv++; /* Only simple time varying variables */
                   8588:       TvarV[ncovv]=Tvar[k];
1.242   ! brouard  8589:       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  8590:       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 */
                   8591:       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  8592:       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);
                   8593:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8594:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8595:       Fixed[k]= 1;
                   8596:       Dummy[k]= 1;
                   8597:       nqtveff++;
                   8598:       modell[k].maintype= VTYPE;
                   8599:       modell[k].subtype= VQ;
                   8600:       ncovv++; /* Only simple time varying variables */
                   8601:       nsq++;
                   8602:       TvarsQ[nsq]=Tvar[k];
                   8603:       TvarsQind[nsq]=k;
                   8604:       TvarV[ncovv]=Tvar[k];
1.242   ! brouard  8605:       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  8606:       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 */
                   8607:       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  8608:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8609:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8610:       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  8611:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8612:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8613:       ncova++;
                   8614:       TvarA[ncova]=Tvar[k];
                   8615:       TvarAind[ncova]=k;
1.231     brouard  8616:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  8617:        Fixed[k]= 2;
                   8618:        Dummy[k]= 2;
                   8619:        modell[k].maintype= ATYPE;
                   8620:        modell[k].subtype= APFD;
                   8621:        /* ncoveff++; */
1.227     brouard  8622:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  8623:        Fixed[k]= 2;
                   8624:        Dummy[k]= 3;
                   8625:        modell[k].maintype= ATYPE;
                   8626:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8627:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8628:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  8629:        Fixed[k]= 3;
                   8630:        Dummy[k]= 2;
                   8631:        modell[k].maintype= ATYPE;
                   8632:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8633:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8634:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8635:        Fixed[k]= 3;
                   8636:        Dummy[k]= 3;
                   8637:        modell[k].maintype= ATYPE;
                   8638:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8639:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8640:       }
                   8641:     }else if (Typevar[k] == 2) {  /* product without age */
                   8642:       k1=Tposprod[k];
                   8643:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  8644:        if(Tvard[k1][2] <=ncovcol){
                   8645:          Fixed[k]= 1;
                   8646:          Dummy[k]= 0;
                   8647:          modell[k].maintype= FTYPE;
                   8648:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8649:          ncovf++; /* Fixed variables without age */
                   8650:          TvarF[ncovf]=Tvar[k];
                   8651:          TvarFind[ncovf]=k;
                   8652:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8653:          Fixed[k]= 0;  /* or 2 ?*/
                   8654:          Dummy[k]= 1;
                   8655:          modell[k].maintype= FTYPE;
                   8656:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8657:          ncovf++; /* Varying variables without age */
                   8658:          TvarF[ncovf]=Tvar[k];
                   8659:          TvarFind[ncovf]=k;
                   8660:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8661:          Fixed[k]= 1;
                   8662:          Dummy[k]= 0;
                   8663:          modell[k].maintype= VTYPE;
                   8664:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8665:          ncovv++; /* Varying variables without age */
                   8666:          TvarV[ncovv]=Tvar[k];
                   8667:          TvarVind[ncovv]=k;
                   8668:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8669:          Fixed[k]= 1;
                   8670:          Dummy[k]= 1;
                   8671:          modell[k].maintype= VTYPE;
                   8672:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8673:          ncovv++; /* Varying variables without age */
                   8674:          TvarV[ncovv]=Tvar[k];
                   8675:          TvarVind[ncovv]=k;
                   8676:        }
1.227     brouard  8677:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  8678:        if(Tvard[k1][2] <=ncovcol){
                   8679:          Fixed[k]= 0;  /* or 2 ?*/
                   8680:          Dummy[k]= 1;
                   8681:          modell[k].maintype= FTYPE;
                   8682:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8683:          ncovf++; /* Fixed variables without age */
                   8684:          TvarF[ncovf]=Tvar[k];
                   8685:          TvarFind[ncovf]=k;
                   8686:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8687:          Fixed[k]= 1;
                   8688:          Dummy[k]= 1;
                   8689:          modell[k].maintype= VTYPE;
                   8690:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8691:          ncovv++; /* Varying variables without age */
                   8692:          TvarV[ncovv]=Tvar[k];
                   8693:          TvarVind[ncovv]=k;
                   8694:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8695:          Fixed[k]= 1;
                   8696:          Dummy[k]= 1;
                   8697:          modell[k].maintype= VTYPE;
                   8698:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8699:          ncovv++; /* Varying variables without age */
                   8700:          TvarV[ncovv]=Tvar[k];
                   8701:          TvarVind[ncovv]=k;
                   8702:          ncovv++; /* Varying variables without age */
                   8703:          TvarV[ncovv]=Tvar[k];
                   8704:          TvarVind[ncovv]=k;
                   8705:        }
1.227     brouard  8706:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  8707:        if(Tvard[k1][2] <=ncovcol){
                   8708:          Fixed[k]= 1;
                   8709:          Dummy[k]= 1;
                   8710:          modell[k].maintype= VTYPE;
                   8711:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8712:          ncovv++; /* Varying variables without age */
                   8713:          TvarV[ncovv]=Tvar[k];
                   8714:          TvarVind[ncovv]=k;
                   8715:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8716:          Fixed[k]= 1;
                   8717:          Dummy[k]= 1;
                   8718:          modell[k].maintype= VTYPE;
                   8719:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8720:          ncovv++; /* Varying variables without age */
                   8721:          TvarV[ncovv]=Tvar[k];
                   8722:          TvarVind[ncovv]=k;
                   8723:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8724:          Fixed[k]= 1;
                   8725:          Dummy[k]= 0;
                   8726:          modell[k].maintype= VTYPE;
                   8727:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8728:          ncovv++; /* Varying variables without age */
                   8729:          TvarV[ncovv]=Tvar[k];
                   8730:          TvarVind[ncovv]=k;
                   8731:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8732:          Fixed[k]= 1;
                   8733:          Dummy[k]= 1;
                   8734:          modell[k].maintype= VTYPE;
                   8735:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   8736:          ncovv++; /* Varying variables without age */
                   8737:          TvarV[ncovv]=Tvar[k];
                   8738:          TvarVind[ncovv]=k;
                   8739:        }
1.227     brouard  8740:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8741:        if(Tvard[k1][2] <=ncovcol){
                   8742:          Fixed[k]= 1;
                   8743:          Dummy[k]= 1;
                   8744:          modell[k].maintype= VTYPE;
                   8745:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   8746:          ncovv++; /* Varying variables without age */
                   8747:          TvarV[ncovv]=Tvar[k];
                   8748:          TvarVind[ncovv]=k;
                   8749:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8750:          Fixed[k]= 1;
                   8751:          Dummy[k]= 1;
                   8752:          modell[k].maintype= VTYPE;
                   8753:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   8754:          ncovv++; /* Varying variables without age */
                   8755:          TvarV[ncovv]=Tvar[k];
                   8756:          TvarVind[ncovv]=k;
                   8757:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8758:          Fixed[k]= 1;
                   8759:          Dummy[k]= 1;
                   8760:          modell[k].maintype= VTYPE;
                   8761:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   8762:          ncovv++; /* Varying variables without age */
                   8763:          TvarV[ncovv]=Tvar[k];
                   8764:          TvarVind[ncovv]=k;
                   8765:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8766:          Fixed[k]= 1;
                   8767:          Dummy[k]= 1;
                   8768:          modell[k].maintype= VTYPE;
                   8769:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   8770:          ncovv++; /* Varying variables without age */
                   8771:          TvarV[ncovv]=Tvar[k];
                   8772:          TvarVind[ncovv]=k;
                   8773:        }
1.227     brouard  8774:       }else{
1.240     brouard  8775:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8776:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8777:       } /*end k1*/
1.225     brouard  8778:     }else{
1.226     brouard  8779:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8780:       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  8781:     }
1.227     brouard  8782:     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  8783:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8784:     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]);
                   8785:   }
                   8786:   /* Searching for doublons in the model */
                   8787:   for(k1=1; k1<= cptcovt;k1++){
                   8788:     for(k2=1; k2 <k1;k2++){
                   8789:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8790:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8791:          if(Tvar[k1]==Tvar[k2]){
                   8792:            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[Tvar[k1]],Dummy[Tvar[k1]]);
                   8793:            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[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
                   8794:            return(1);
                   8795:          }
                   8796:        }else if (Typevar[k1] ==2){
                   8797:          k3=Tposprod[k1];
                   8798:          k4=Tposprod[k2];
                   8799:          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])) ){
                   8800:            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]]);
                   8801:            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);
                   8802:            return(1);
                   8803:          }
                   8804:        }
1.227     brouard  8805:       }
                   8806:     }
1.225     brouard  8807:   }
                   8808:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8809:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8810:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8811:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8812:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8813:   /*endread:*/
1.225     brouard  8814:   printf("Exiting decodemodel: ");
                   8815:   return (1);
1.136     brouard  8816: }
                   8817: 
1.169     brouard  8818: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8819: {
                   8820:   int i, m;
1.218     brouard  8821:   int firstone=0;
                   8822:   
1.136     brouard  8823:   for (i=1; i<=imx; i++) {
                   8824:     for(m=2; (m<= maxwav); m++) {
                   8825:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8826:        anint[m][i]=9999;
1.216     brouard  8827:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8828:          s[m][i]=-1;
1.136     brouard  8829:       }
                   8830:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8831:        *nberr = *nberr + 1;
1.218     brouard  8832:        if(firstone == 0){
                   8833:          firstone=1;
                   8834:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
                   8835:        }
                   8836:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
1.136     brouard  8837:        s[m][i]=-1;
                   8838:       }
                   8839:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8840:        (*nberr)++;
1.136     brouard  8841:        printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]); 
                   8842:        fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]); 
                   8843:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8844:       }
                   8845:     }
                   8846:   }
                   8847: 
                   8848:   for (i=1; i<=imx; i++)  {
                   8849:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8850:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8851:       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  8852:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8853:          if(agedc[i]>0){
                   8854:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8855:              agev[m][i]=agedc[i];
1.214     brouard  8856:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8857:            }else {
1.136     brouard  8858:              if ((int)andc[i]!=9999){
                   8859:                nbwarn++;
                   8860:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8861:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8862:                agev[m][i]=-1;
                   8863:              }
                   8864:            }
1.169     brouard  8865:          } /* agedc > 0 */
1.214     brouard  8866:        } /* end if */
1.136     brouard  8867:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8868:                                 years but with the precision of a month */
                   8869:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8870:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8871:            agev[m][i]=1;
                   8872:          else if(agev[m][i] < *agemin){ 
                   8873:            *agemin=agev[m][i];
                   8874:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8875:          }
                   8876:          else if(agev[m][i] >*agemax){
                   8877:            *agemax=agev[m][i];
1.156     brouard  8878:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8879:          }
                   8880:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8881:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8882:        } /* en if 9*/
1.136     brouard  8883:        else { /* =9 */
1.214     brouard  8884:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8885:          agev[m][i]=1;
                   8886:          s[m][i]=-1;
                   8887:        }
                   8888:       }
1.214     brouard  8889:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8890:        agev[m][i]=1;
1.214     brouard  8891:       else{
                   8892:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8893:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8894:        agev[m][i]=0;
                   8895:       }
                   8896:     } /* End for lastpass */
                   8897:   }
1.136     brouard  8898:     
                   8899:   for (i=1; i<=imx; i++)  {
                   8900:     for(m=firstpass; (m<=lastpass); m++){
                   8901:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8902:        (*nberr)++;
1.136     brouard  8903:        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);     
                   8904:        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);     
                   8905:        return 1;
                   8906:       }
                   8907:     }
                   8908:   }
                   8909: 
                   8910:   /*for (i=1; i<=imx; i++){
                   8911:   for (m=firstpass; (m<lastpass); m++){
                   8912:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8913: }
                   8914: 
                   8915: }*/
                   8916: 
                   8917: 
1.139     brouard  8918:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8919:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8920: 
                   8921:   return (0);
1.164     brouard  8922:  /* endread:*/
1.136     brouard  8923:     printf("Exiting calandcheckages: ");
                   8924:     return (1);
                   8925: }
                   8926: 
1.172     brouard  8927: #if defined(_MSC_VER)
                   8928: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8929: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8930: //#include "stdafx.h"
                   8931: //#include <stdio.h>
                   8932: //#include <tchar.h>
                   8933: //#include <windows.h>
                   8934: //#include <iostream>
                   8935: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8936: 
                   8937: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8938: 
                   8939: BOOL IsWow64()
                   8940: {
                   8941:        BOOL bIsWow64 = FALSE;
                   8942: 
                   8943:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8944:        //  (HANDLE, PBOOL);
                   8945: 
                   8946:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8947: 
                   8948:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8949:        const char funcName[] = "IsWow64Process";
                   8950:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8951:                GetProcAddress(module, funcName);
                   8952: 
                   8953:        if (NULL != fnIsWow64Process)
                   8954:        {
                   8955:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8956:                        &bIsWow64))
                   8957:                        //throw std::exception("Unknown error");
                   8958:                        printf("Unknown error\n");
                   8959:        }
                   8960:        return bIsWow64 != FALSE;
                   8961: }
                   8962: #endif
1.177     brouard  8963: 
1.191     brouard  8964: void syscompilerinfo(int logged)
1.167     brouard  8965:  {
                   8966:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8967:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8968:    /* /GS /W3 /Gy
                   8969:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8970:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8971:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8972:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8973:    */ 
                   8974:    /* 64 bits */
1.185     brouard  8975:    /*
                   8976:      /GS /W3 /Gy
                   8977:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8978:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8979:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8980:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8981:    /* Optimization are useless and O3 is slower than O2 */
                   8982:    /*
                   8983:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8984:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8985:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8986:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8987:    */
1.186     brouard  8988:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  8989:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   8990:       /PDB:"visual studio
                   8991:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   8992:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   8993:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   8994:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   8995:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   8996:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   8997:       uiAccess='false'"
                   8998:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   8999:       /NOLOGO /TLBID:1
                   9000:    */
1.177     brouard  9001: #if defined __INTEL_COMPILER
1.178     brouard  9002: #if defined(__GNUC__)
                   9003:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   9004: #endif
1.177     brouard  9005: #elif defined(__GNUC__) 
1.179     brouard  9006: #ifndef  __APPLE__
1.174     brouard  9007: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  9008: #endif
1.177     brouard  9009:    struct utsname sysInfo;
1.178     brouard  9010:    int cross = CROSS;
                   9011:    if (cross){
                   9012:           printf("Cross-");
1.191     brouard  9013:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  9014:    }
1.174     brouard  9015: #endif
                   9016: 
1.171     brouard  9017: #include <stdint.h>
1.178     brouard  9018: 
1.191     brouard  9019:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  9020: #if defined(__clang__)
1.191     brouard  9021:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  9022: #endif
                   9023: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  9024:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  9025: #endif
                   9026: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  9027:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  9028: #endif
                   9029: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  9030:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  9031: #endif
                   9032: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  9033:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  9034: #endif
                   9035: #if defined(_MSC_VER)
1.191     brouard  9036:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  9037: #endif
                   9038: #if defined(__PGI)
1.191     brouard  9039:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  9040: #endif
                   9041: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  9042:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  9043: #endif
1.191     brouard  9044:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  9045:    
1.167     brouard  9046: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   9047: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   9048:     // Windows (x64 and x86)
1.191     brouard  9049:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  9050: #elif __unix__ // all unices, not all compilers
                   9051:     // Unix
1.191     brouard  9052:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  9053: #elif __linux__
                   9054:     // linux
1.191     brouard  9055:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9056: #elif __APPLE__
1.174     brouard  9057:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9058:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9059: #endif
                   9060: 
                   9061: /*  __MINGW32__          */
                   9062: /*  __CYGWIN__  */
                   9063: /* __MINGW64__  */
                   9064: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9065: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9066: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9067: /* _WIN64  // Defined for applications for Win64. */
                   9068: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9069: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9070: 
1.167     brouard  9071: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9072:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9073: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9074:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9075: #else
1.191     brouard  9076:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9077: #endif
                   9078: 
1.169     brouard  9079: #if defined(__GNUC__)
                   9080: # if defined(__GNUC_PATCHLEVEL__)
                   9081: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9082:                             + __GNUC_MINOR__ * 100 \
                   9083:                             + __GNUC_PATCHLEVEL__)
                   9084: # else
                   9085: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9086:                             + __GNUC_MINOR__ * 100)
                   9087: # endif
1.174     brouard  9088:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9089:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9090: 
                   9091:    if (uname(&sysInfo) != -1) {
                   9092:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9093:         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  9094:    }
                   9095:    else
                   9096:       perror("uname() error");
1.179     brouard  9097:    //#ifndef __INTEL_COMPILER 
                   9098: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9099:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9100:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9101: #endif
1.169     brouard  9102: #endif
1.172     brouard  9103: 
                   9104:    //   void main()
                   9105:    //   {
1.169     brouard  9106: #if defined(_MSC_VER)
1.174     brouard  9107:    if (IsWow64()){
1.191     brouard  9108:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9109:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9110:    }
                   9111:    else{
1.191     brouard  9112:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9113:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9114:    }
1.172     brouard  9115:    //     printf("\nPress Enter to continue...");
                   9116:    //     getchar();
                   9117:    //   }
                   9118: 
1.169     brouard  9119: #endif
                   9120:    
1.167     brouard  9121: 
1.219     brouard  9122: }
1.136     brouard  9123: 
1.219     brouard  9124: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9125:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9126:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9127:   /* double ftolpl = 1.e-10; */
1.180     brouard  9128:   double age, agebase, agelim;
1.203     brouard  9129:   double tot;
1.180     brouard  9130: 
1.202     brouard  9131:   strcpy(filerespl,"PL_");
                   9132:   strcat(filerespl,fileresu);
                   9133:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9134:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9135:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9136:   }
1.227     brouard  9137:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9138:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9139:   pstamp(ficrespl);
1.203     brouard  9140:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9141:   fprintf(ficrespl,"#Age ");
                   9142:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9143:   fprintf(ficrespl,"\n");
1.180     brouard  9144:   
1.219     brouard  9145:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9146: 
1.219     brouard  9147:   agebase=ageminpar;
                   9148:   agelim=agemaxpar;
1.180     brouard  9149: 
1.227     brouard  9150:   /* i1=pow(2,ncoveff); */
1.234     brouard  9151:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9152:   if (cptcovn < 1){i1=1;}
1.180     brouard  9153: 
1.238     brouard  9154:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9155:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9156:       if(TKresult[nres]!= k)
                   9157:        continue;
1.235     brouard  9158: 
1.238     brouard  9159:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9160:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9161:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9162:       /* k=k+1; */
                   9163:       /* to clean */
                   9164:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9165:       fprintf(ficrespl,"#******");
                   9166:       printf("#******");
                   9167:       fprintf(ficlog,"#******");
                   9168:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9169:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9170:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9171:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9172:       }
                   9173:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9174:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9175:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9176:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9177:       }
                   9178:       fprintf(ficrespl,"******\n");
                   9179:       printf("******\n");
                   9180:       fprintf(ficlog,"******\n");
                   9181:       if(invalidvarcomb[k]){
                   9182:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9183:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9184:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9185:        continue;
                   9186:       }
1.219     brouard  9187: 
1.238     brouard  9188:       fprintf(ficrespl,"#Age ");
                   9189:       for(j=1;j<=cptcoveff;j++) {
                   9190:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9191:       }
                   9192:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9193:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9194:     
1.238     brouard  9195:       for (age=agebase; age<=agelim; age++){
                   9196:        /* for (age=agebase; age<=agebase; age++){ */
                   9197:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9198:        fprintf(ficrespl,"%.0f ",age );
                   9199:        for(j=1;j<=cptcoveff;j++)
                   9200:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9201:        tot=0.;
                   9202:        for(i=1; i<=nlstate;i++){
                   9203:          tot +=  prlim[i][i];
                   9204:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9205:        }
                   9206:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9207:       } /* Age */
                   9208:       /* was end of cptcod */
                   9209:     } /* cptcov */
                   9210:   } /* nres */
1.219     brouard  9211:   return 0;
1.180     brouard  9212: }
                   9213: 
1.218     brouard  9214: 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){
                   9215:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9216:        
                   9217:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9218:    * at any age between ageminpar and agemaxpar
                   9219:         */
1.235     brouard  9220:   int i, j, k, i1, nres=0 ;
1.217     brouard  9221:   /* double ftolpl = 1.e-10; */
                   9222:   double age, agebase, agelim;
                   9223:   double tot;
1.218     brouard  9224:   /* double ***mobaverage; */
                   9225:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9226: 
                   9227:   strcpy(fileresplb,"PLB_");
                   9228:   strcat(fileresplb,fileresu);
                   9229:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9230:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9231:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9232:   }
                   9233:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9234:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9235:   pstamp(ficresplb);
                   9236:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9237:   fprintf(ficresplb,"#Age ");
                   9238:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9239:   fprintf(ficresplb,"\n");
                   9240:   
1.218     brouard  9241:   
                   9242:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9243:   
                   9244:   agebase=ageminpar;
                   9245:   agelim=agemaxpar;
                   9246:   
                   9247:   
1.227     brouard  9248:   i1=pow(2,cptcoveff);
1.218     brouard  9249:   if (cptcovn < 1){i1=1;}
1.227     brouard  9250:   
1.238     brouard  9251:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9252:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9253:       if(TKresult[nres]!= k)
                   9254:        continue;
                   9255:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9256:       fprintf(ficresplb,"#******");
                   9257:       printf("#******");
                   9258:       fprintf(ficlog,"#******");
                   9259:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9260:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9261:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9262:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9263:       }
                   9264:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9265:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9266:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9267:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9268:       }
                   9269:       fprintf(ficresplb,"******\n");
                   9270:       printf("******\n");
                   9271:       fprintf(ficlog,"******\n");
                   9272:       if(invalidvarcomb[k]){
                   9273:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9274:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9275:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9276:        continue;
                   9277:       }
1.218     brouard  9278:     
1.238     brouard  9279:       fprintf(ficresplb,"#Age ");
                   9280:       for(j=1;j<=cptcoveff;j++) {
                   9281:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9282:       }
                   9283:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9284:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9285:     
                   9286:     
1.238     brouard  9287:       for (age=agebase; age<=agelim; age++){
                   9288:        /* for (age=agebase; age<=agebase; age++){ */
                   9289:        if(mobilavproj > 0){
                   9290:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9291:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242   ! brouard  9292:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  9293:        }else if (mobilavproj == 0){
                   9294:          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);
                   9295:          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);
                   9296:          exit(1);
                   9297:        }else{
                   9298:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242   ! brouard  9299:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.238     brouard  9300:        }
                   9301:        fprintf(ficresplb,"%.0f ",age );
                   9302:        for(j=1;j<=cptcoveff;j++)
                   9303:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9304:        tot=0.;
                   9305:        for(i=1; i<=nlstate;i++){
                   9306:          tot +=  bprlim[i][i];
                   9307:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9308:        }
                   9309:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9310:       } /* Age */
                   9311:       /* was end of cptcod */
                   9312:     } /* end of any combination */
                   9313:   } /* end of nres */  
1.218     brouard  9314:   /* hBijx(p, bage, fage); */
                   9315:   /* fclose(ficrespijb); */
                   9316:   
                   9317:   return 0;
1.217     brouard  9318: }
1.218     brouard  9319:  
1.180     brouard  9320: int hPijx(double *p, int bage, int fage){
                   9321:     /*------------- h Pij x at various ages ------------*/
                   9322: 
                   9323:   int stepsize;
                   9324:   int agelim;
                   9325:   int hstepm;
                   9326:   int nhstepm;
1.235     brouard  9327:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9328: 
                   9329:   double agedeb;
                   9330:   double ***p3mat;
                   9331: 
1.201     brouard  9332:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9333:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9334:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9335:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9336:     }
                   9337:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9338:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9339:   
                   9340:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9341:     /*if (stepm<=24) stepsize=2;*/
                   9342: 
                   9343:     agelim=AGESUP;
                   9344:     hstepm=stepsize*YEARM; /* Every year of age */
                   9345:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9346:                
1.180     brouard  9347:     /* hstepm=1;   aff par mois*/
                   9348:     pstamp(ficrespij);
                   9349:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9350:     i1= pow(2,cptcoveff);
1.218     brouard  9351:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9352:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9353:                /*      k=k+1;  */
1.235     brouard  9354:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9355:     for(k=1; k<=i1;k++){
                   9356:       if(TKresult[nres]!= k)
                   9357:        continue;
1.183     brouard  9358:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9359:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9360:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9361:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9362:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9363:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9364:       }
1.183     brouard  9365:       fprintf(ficrespij,"******\n");
                   9366:       
                   9367:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9368:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9369:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9370:        
                   9371:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9372:        
1.183     brouard  9373:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9374:        oldm=oldms;savm=savms;
1.235     brouard  9375:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9376:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9377:        for(i=1; i<=nlstate;i++)
                   9378:          for(j=1; j<=nlstate+ndeath;j++)
                   9379:            fprintf(ficrespij," %1d-%1d",i,j);
                   9380:        fprintf(ficrespij,"\n");
                   9381:        for (h=0; h<=nhstepm; h++){
                   9382:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9383:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9384:          for(i=1; i<=nlstate;i++)
                   9385:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9386:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9387:          fprintf(ficrespij,"\n");
                   9388:        }
1.183     brouard  9389:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9390:        fprintf(ficrespij,"\n");
                   9391:       }
1.180     brouard  9392:       /*}*/
                   9393:     }
1.218     brouard  9394:     return 0;
1.180     brouard  9395: }
1.218     brouard  9396:  
                   9397:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9398:     /*------------- h Bij x at various ages ------------*/
                   9399: 
                   9400:   int stepsize;
1.218     brouard  9401:   /* int agelim; */
                   9402:        int ageminl;
1.217     brouard  9403:   int hstepm;
                   9404:   int nhstepm;
1.238     brouard  9405:   int h, i, i1, j, k, nres;
1.218     brouard  9406:        
1.217     brouard  9407:   double agedeb;
                   9408:   double ***p3mat;
1.218     brouard  9409:        
                   9410:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9411:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9412:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9413:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9414:   }
                   9415:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9416:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9417:   
                   9418:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9419:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9420:   
1.218     brouard  9421:   /* agelim=AGESUP; */
                   9422:   ageminl=30;
                   9423:   hstepm=stepsize*YEARM; /* Every year of age */
                   9424:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9425:   
                   9426:   /* hstepm=1;   aff par mois*/
                   9427:   pstamp(ficrespijb);
                   9428:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9429:   i1= pow(2,cptcoveff);
1.218     brouard  9430:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9431:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9432:   /*   k=k+1;  */
1.238     brouard  9433:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9434:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9435:       if(TKresult[nres]!= k)
                   9436:        continue;
                   9437:       fprintf(ficrespijb,"\n#****** ");
                   9438:       for(j=1;j<=cptcoveff;j++)
                   9439:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9440:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9441:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9442:       }
                   9443:       fprintf(ficrespijb,"******\n");
                   9444:       if(invalidvarcomb[k]){
                   9445:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9446:        continue;
                   9447:       }
                   9448:       
                   9449:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9450:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9451:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9452:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9453:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9454:        
                   9455:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9456:        
                   9457:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9458:        /* oldm=oldms;savm=savms; */
                   9459:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9460:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9461:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   9462:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
1.217     brouard  9463:        for(i=1; i<=nlstate;i++)
                   9464:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9465:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9466:        fprintf(ficrespijb,"\n");
1.238     brouard  9467:        for (h=0; h<=nhstepm; h++){
                   9468:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9469:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9470:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9471:          for(i=1; i<=nlstate;i++)
                   9472:            for(j=1; j<=nlstate+ndeath;j++)
                   9473:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9474:          fprintf(ficrespijb,"\n");
                   9475:        }
                   9476:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9477:        fprintf(ficrespijb,"\n");
                   9478:       } /* end age deb */
                   9479:     } /* end combination */
                   9480:   } /* end nres */
1.218     brouard  9481:   return 0;
                   9482:  } /*  hBijx */
1.217     brouard  9483: 
1.180     brouard  9484: 
1.136     brouard  9485: /***********************************************/
                   9486: /**************** Main Program *****************/
                   9487: /***********************************************/
                   9488: 
                   9489: int main(int argc, char *argv[])
                   9490: {
                   9491: #ifdef GSL
                   9492:   const gsl_multimin_fminimizer_type *T;
                   9493:   size_t iteri = 0, it;
                   9494:   int rval = GSL_CONTINUE;
                   9495:   int status = GSL_SUCCESS;
                   9496:   double ssval;
                   9497: #endif
                   9498:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9499:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9500:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9501:   int jj, ll, li, lj, lk;
1.136     brouard  9502:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9503:   int num_filled;
1.136     brouard  9504:   int itimes;
                   9505:   int NDIM=2;
                   9506:   int vpopbased=0;
1.235     brouard  9507:   int nres=0;
1.136     brouard  9508: 
1.164     brouard  9509:   char ca[32], cb[32];
1.136     brouard  9510:   /*  FILE *fichtm; *//* Html File */
                   9511:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9512:   struct stat info;
1.191     brouard  9513:   double agedeb=0.;
1.194     brouard  9514: 
                   9515:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9516:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9517: 
1.165     brouard  9518:   double fret;
1.191     brouard  9519:   double dum=0.; /* Dummy variable */
1.136     brouard  9520:   double ***p3mat;
1.218     brouard  9521:   /* double ***mobaverage; */
1.164     brouard  9522: 
                   9523:   char line[MAXLINE];
1.197     brouard  9524:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9525: 
1.234     brouard  9526:   char  modeltemp[MAXLINE];
1.230     brouard  9527:   char resultline[MAXLINE];
                   9528:   
1.136     brouard  9529:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9530:   char *tok, *val; /* pathtot */
1.136     brouard  9531:   int firstobs=1, lastobs=10;
1.195     brouard  9532:   int c,  h , cpt, c2;
1.191     brouard  9533:   int jl=0;
                   9534:   int i1, j1, jk, stepsize=0;
1.194     brouard  9535:   int count=0;
                   9536: 
1.164     brouard  9537:   int *tab; 
1.136     brouard  9538:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9539:   int backcast=0;
1.136     brouard  9540:   int mobilav=0,popforecast=0;
1.191     brouard  9541:   int hstepm=0, nhstepm=0;
1.136     brouard  9542:   int agemortsup;
                   9543:   float  sumlpop=0.;
                   9544:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9545:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9546: 
1.191     brouard  9547:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9548:   double ftolpl=FTOL;
                   9549:   double **prlim;
1.217     brouard  9550:   double **bprlim;
1.136     brouard  9551:   double ***param; /* Matrix of parameters */
                   9552:   double  *p;
                   9553:   double **matcov; /* Matrix of covariance */
1.203     brouard  9554:   double **hess; /* Hessian matrix */
1.136     brouard  9555:   double ***delti3; /* Scale */
                   9556:   double *delti; /* Scale */
                   9557:   double ***eij, ***vareij;
                   9558:   double **varpl; /* Variances of prevalence limits by age */
                   9559:   double *epj, vepp;
1.164     brouard  9560: 
1.136     brouard  9561:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9562:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9563: 
1.136     brouard  9564:   double **ximort;
1.145     brouard  9565:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9566:   int *dcwave;
                   9567: 
1.164     brouard  9568:   char z[1]="c";
1.136     brouard  9569: 
                   9570:   /*char  *strt;*/
                   9571:   char strtend[80];
1.126     brouard  9572: 
1.164     brouard  9573: 
1.126     brouard  9574: /*   setlocale (LC_ALL, ""); */
                   9575: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9576: /*   textdomain (PACKAGE); */
                   9577: /*   setlocale (LC_CTYPE, ""); */
                   9578: /*   setlocale (LC_MESSAGES, ""); */
                   9579: 
                   9580:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9581:   rstart_time = time(NULL);  
                   9582:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9583:   start_time = *localtime(&rstart_time);
1.126     brouard  9584:   curr_time=start_time;
1.157     brouard  9585:   /*tml = *localtime(&start_time.tm_sec);*/
                   9586:   /* strcpy(strstart,asctime(&tml)); */
                   9587:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9588: 
                   9589: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9590: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9591: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9592: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9593: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9594: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9595: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9596: /*   strt=asctime(&tmg); */
                   9597: /*   printf("Time(after) =%s",strstart);  */
                   9598: /*  (void) time (&time_value);
                   9599: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9600: *  tm = *localtime(&time_value);
                   9601: *  strstart=asctime(&tm);
                   9602: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9603: */
                   9604: 
                   9605:   nberr=0; /* Number of errors and warnings */
                   9606:   nbwarn=0;
1.184     brouard  9607: #ifdef WIN32
                   9608:   _getcwd(pathcd, size);
                   9609: #else
1.126     brouard  9610:   getcwd(pathcd, size);
1.184     brouard  9611: #endif
1.191     brouard  9612:   syscompilerinfo(0);
1.196     brouard  9613:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9614:   if(argc <=1){
                   9615:     printf("\nEnter the parameter file name: ");
1.205     brouard  9616:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9617:       printf("ERROR Empty parameter file name\n");
                   9618:       goto end;
                   9619:     }
1.126     brouard  9620:     i=strlen(pathr);
                   9621:     if(pathr[i-1]=='\n')
                   9622:       pathr[i-1]='\0';
1.156     brouard  9623:     i=strlen(pathr);
1.205     brouard  9624:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9625:       pathr[i-1]='\0';
1.205     brouard  9626:     }
                   9627:     i=strlen(pathr);
                   9628:     if( i==0 ){
                   9629:       printf("ERROR Empty parameter file name\n");
                   9630:       goto end;
                   9631:     }
                   9632:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9633:       printf("Pathr |%s|\n",pathr);
                   9634:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9635:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9636:       strcpy (pathtot, val);
                   9637:       if(pathr[0] == '\0') break; /* Dirty */
                   9638:     }
                   9639:   }
                   9640:   else{
                   9641:     strcpy(pathtot,argv[1]);
                   9642:   }
                   9643:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9644:   /*cygwin_split_path(pathtot,path,optionfile);
                   9645:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9646:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9647: 
                   9648:   /* Split argv[0], imach program to get pathimach */
                   9649:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9650:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9651:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9652:  /*   strcpy(pathimach,argv[0]); */
                   9653:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9654:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9655:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9656: #ifdef WIN32
                   9657:   _chdir(path); /* Can be a relative path */
                   9658:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9659: #else
1.126     brouard  9660:   chdir(path); /* Can be a relative path */
1.184     brouard  9661:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9662: #endif
                   9663:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9664:   strcpy(command,"mkdir ");
                   9665:   strcat(command,optionfilefiname);
                   9666:   if((outcmd=system(command)) != 0){
1.169     brouard  9667:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9668:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9669:     /* fclose(ficlog); */
                   9670: /*     exit(1); */
                   9671:   }
                   9672: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9673: /*     perror("mkdir"); */
                   9674: /*   } */
                   9675: 
                   9676:   /*-------- arguments in the command line --------*/
                   9677: 
1.186     brouard  9678:   /* Main Log file */
1.126     brouard  9679:   strcat(filelog, optionfilefiname);
                   9680:   strcat(filelog,".log");    /* */
                   9681:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9682:     printf("Problem with logfile %s\n",filelog);
                   9683:     goto end;
                   9684:   }
                   9685:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9686:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9687:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9688:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9689:  path=%s \n\
                   9690:  optionfile=%s\n\
                   9691:  optionfilext=%s\n\
1.156     brouard  9692:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9693: 
1.197     brouard  9694:   syscompilerinfo(1);
1.167     brouard  9695: 
1.126     brouard  9696:   printf("Local time (at start):%s",strstart);
                   9697:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9698:   fflush(ficlog);
                   9699: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9700: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9701: 
                   9702:   /* */
                   9703:   strcpy(fileres,"r");
                   9704:   strcat(fileres, optionfilefiname);
1.201     brouard  9705:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9706:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9707:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9708: 
1.186     brouard  9709:   /* Main ---------arguments file --------*/
1.126     brouard  9710: 
                   9711:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9712:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9713:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9714:     fflush(ficlog);
1.149     brouard  9715:     /* goto end; */
                   9716:     exit(70); 
1.126     brouard  9717:   }
                   9718: 
                   9719: 
                   9720: 
                   9721:   strcpy(filereso,"o");
1.201     brouard  9722:   strcat(filereso,fileresu);
1.126     brouard  9723:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9724:     printf("Problem with Output resultfile: %s\n", filereso);
                   9725:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9726:     fflush(ficlog);
                   9727:     goto end;
                   9728:   }
                   9729: 
                   9730:   /* Reads comments: lines beginning with '#' */
                   9731:   numlinepar=0;
1.197     brouard  9732: 
                   9733:     /* First parameter line */
                   9734:   while(fgets(line, MAXLINE, ficpar)) {
                   9735:     /* If line starts with a # it is a comment */
                   9736:     if (line[0] == '#') {
                   9737:       numlinepar++;
                   9738:       fputs(line,stdout);
                   9739:       fputs(line,ficparo);
                   9740:       fputs(line,ficlog);
                   9741:       continue;
                   9742:     }else
                   9743:       break;
                   9744:   }
                   9745:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9746:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9747:     if (num_filled != 5) {
                   9748:       printf("Should be 5 parameters\n");
                   9749:     }
1.126     brouard  9750:     numlinepar++;
1.197     brouard  9751:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9752:   }
                   9753:   /* Second parameter line */
                   9754:   while(fgets(line, MAXLINE, ficpar)) {
                   9755:     /* If line starts with a # it is a comment */
                   9756:     if (line[0] == '#') {
                   9757:       numlinepar++;
                   9758:       fputs(line,stdout);
                   9759:       fputs(line,ficparo);
                   9760:       fputs(line,ficlog);
                   9761:       continue;
                   9762:     }else
                   9763:       break;
                   9764:   }
1.223     brouard  9765:   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", \
                   9766:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9767:     if (num_filled != 11) {
                   9768:       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  9769:       printf("but line=%s\n",line);
1.197     brouard  9770:     }
1.223     brouard  9771:     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.126     brouard  9772:   }
1.203     brouard  9773:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9774:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9775:   /* Third parameter line */
                   9776:   while(fgets(line, MAXLINE, ficpar)) {
                   9777:     /* If line starts with a # it is a comment */
                   9778:     if (line[0] == '#') {
                   9779:       numlinepar++;
                   9780:       fputs(line,stdout);
                   9781:       fputs(line,ficparo);
                   9782:       fputs(line,ficlog);
                   9783:       continue;
                   9784:     }else
                   9785:       break;
                   9786:   }
1.201     brouard  9787:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9788:     if (num_filled == 0)
                   9789:             model[0]='\0';
                   9790:     else if (num_filled != 1){
1.197     brouard  9791:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9792:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9793:       model[0]='\0';
                   9794:       goto end;
                   9795:     }
                   9796:     else{
                   9797:       if (model[0]=='+'){
                   9798:        for(i=1; i<=strlen(model);i++)
                   9799:          modeltemp[i-1]=model[i];
1.201     brouard  9800:        strcpy(model,modeltemp); 
1.197     brouard  9801:       }
                   9802:     }
1.199     brouard  9803:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9804:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9805:   }
                   9806:   /* 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); */
                   9807:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9808:   /* 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.223     brouard  9809:   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);
                   9810:   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  9811:   fflush(ficlog);
1.190     brouard  9812:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9813:   if(model[0]=='#'){
1.187     brouard  9814:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9815:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9816:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9817:     if(mle != -1){
                   9818:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9819:       exit(1);
                   9820:     }
                   9821:   }
1.126     brouard  9822:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9823:     ungetc(c,ficpar);
                   9824:     fgets(line, MAXLINE, ficpar);
                   9825:     numlinepar++;
1.195     brouard  9826:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9827:       z[0]=line[1];
                   9828:     }
                   9829:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9830:     fputs(line, stdout);
                   9831:     //puts(line);
1.126     brouard  9832:     fputs(line,ficparo);
                   9833:     fputs(line,ficlog);
                   9834:   }
                   9835:   ungetc(c,ficpar);
                   9836: 
                   9837:    
1.145     brouard  9838:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9839:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9840:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9841:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9842:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9843:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9844:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9845:   */
                   9846:   if (strlen(model)>1) 
1.187     brouard  9847:     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  9848:   else
1.187     brouard  9849:     ncovmodel=2; /* Constant and age */
1.133     brouard  9850:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9851:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9852:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9853:     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);
                   9854:     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);
                   9855:     fflush(stdout);
                   9856:     fclose (ficlog);
                   9857:     goto end;
                   9858:   }
1.126     brouard  9859:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9860:   delti=delti3[1][1];
                   9861:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9862:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   9863:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9864:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9865:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9866:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9867:     fclose (ficparo);
                   9868:     fclose (ficlog);
                   9869:     goto end;
                   9870:     exit(0);
1.220     brouard  9871:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9872:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9873:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9874:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9875:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9876:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9877:     hess=matrix(1,npar,1,npar);
1.220     brouard  9878:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9879:     /* Read guessed parameters */
1.126     brouard  9880:     /* Reads comments: lines beginning with '#' */
                   9881:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9882:       ungetc(c,ficpar);
                   9883:       fgets(line, MAXLINE, ficpar);
                   9884:       numlinepar++;
1.141     brouard  9885:       fputs(line,stdout);
1.126     brouard  9886:       fputs(line,ficparo);
                   9887:       fputs(line,ficlog);
                   9888:     }
                   9889:     ungetc(c,ficpar);
                   9890:     
                   9891:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9892:     for(i=1; i <=nlstate; i++){
1.234     brouard  9893:       j=0;
1.126     brouard  9894:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9895:        if(jj==i) continue;
                   9896:        j++;
                   9897:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9898:        if ((i1 != i) || (j1 != jj)){
                   9899:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9900: It might be a problem of design; if ncovcol and the model are correct\n \
                   9901: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9902:          exit(1);
                   9903:        }
                   9904:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9905:        if(mle==1)
                   9906:          printf("%1d%1d",i,jj);
                   9907:        fprintf(ficlog,"%1d%1d",i,jj);
                   9908:        for(k=1; k<=ncovmodel;k++){
                   9909:          fscanf(ficpar," %lf",&param[i][j][k]);
                   9910:          if(mle==1){
                   9911:            printf(" %lf",param[i][j][k]);
                   9912:            fprintf(ficlog," %lf",param[i][j][k]);
                   9913:          }
                   9914:          else
                   9915:            fprintf(ficlog," %lf",param[i][j][k]);
                   9916:          fprintf(ficparo," %lf",param[i][j][k]);
                   9917:        }
                   9918:        fscanf(ficpar,"\n");
                   9919:        numlinepar++;
                   9920:        if(mle==1)
                   9921:          printf("\n");
                   9922:        fprintf(ficlog,"\n");
                   9923:        fprintf(ficparo,"\n");
1.126     brouard  9924:       }
                   9925:     }  
                   9926:     fflush(ficlog);
1.234     brouard  9927:     
1.145     brouard  9928:     /* Reads scales values */
1.126     brouard  9929:     p=param[1][1];
                   9930:     
                   9931:     /* Reads comments: lines beginning with '#' */
                   9932:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9933:       ungetc(c,ficpar);
                   9934:       fgets(line, MAXLINE, ficpar);
                   9935:       numlinepar++;
1.141     brouard  9936:       fputs(line,stdout);
1.126     brouard  9937:       fputs(line,ficparo);
                   9938:       fputs(line,ficlog);
                   9939:     }
                   9940:     ungetc(c,ficpar);
                   9941: 
                   9942:     for(i=1; i <=nlstate; i++){
                   9943:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  9944:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9945:        if ( (i1-i) * (j1-j) != 0){
                   9946:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9947:          exit(1);
                   9948:        }
                   9949:        printf("%1d%1d",i,j);
                   9950:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9951:        fprintf(ficlog,"%1d%1d",i1,j1);
                   9952:        for(k=1; k<=ncovmodel;k++){
                   9953:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9954:          printf(" %le",delti3[i][j][k]);
                   9955:          fprintf(ficparo," %le",delti3[i][j][k]);
                   9956:          fprintf(ficlog," %le",delti3[i][j][k]);
                   9957:        }
                   9958:        fscanf(ficpar,"\n");
                   9959:        numlinepar++;
                   9960:        printf("\n");
                   9961:        fprintf(ficparo,"\n");
                   9962:        fprintf(ficlog,"\n");
1.126     brouard  9963:       }
                   9964:     }
                   9965:     fflush(ficlog);
1.234     brouard  9966:     
1.145     brouard  9967:     /* Reads covariance matrix */
1.126     brouard  9968:     delti=delti3[1][1];
1.220     brouard  9969:                
                   9970:                
1.126     brouard  9971:     /* 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  9972:                
1.126     brouard  9973:     /* Reads comments: lines beginning with '#' */
                   9974:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9975:       ungetc(c,ficpar);
                   9976:       fgets(line, MAXLINE, ficpar);
                   9977:       numlinepar++;
1.141     brouard  9978:       fputs(line,stdout);
1.126     brouard  9979:       fputs(line,ficparo);
                   9980:       fputs(line,ficlog);
                   9981:     }
                   9982:     ungetc(c,ficpar);
1.220     brouard  9983:                
1.126     brouard  9984:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9985:     hess=matrix(1,npar,1,npar);
1.131     brouard  9986:     for(i=1; i <=npar; i++)
                   9987:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  9988:                
1.194     brouard  9989:     /* Scans npar lines */
1.126     brouard  9990:     for(i=1; i <=npar; i++){
1.226     brouard  9991:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  9992:       if(count != 3){
1.226     brouard  9993:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9994: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9995: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9996:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9997: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9998: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9999:        exit(1);
1.220     brouard  10000:       }else{
1.226     brouard  10001:        if(mle==1)
                   10002:          printf("%1d%1d%d",i1,j1,jk);
                   10003:       }
                   10004:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   10005:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  10006:       for(j=1; j <=i; j++){
1.226     brouard  10007:        fscanf(ficpar," %le",&matcov[i][j]);
                   10008:        if(mle==1){
                   10009:          printf(" %.5le",matcov[i][j]);
                   10010:        }
                   10011:        fprintf(ficlog," %.5le",matcov[i][j]);
                   10012:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  10013:       }
                   10014:       fscanf(ficpar,"\n");
                   10015:       numlinepar++;
                   10016:       if(mle==1)
1.220     brouard  10017:                                printf("\n");
1.126     brouard  10018:       fprintf(ficlog,"\n");
                   10019:       fprintf(ficparo,"\n");
                   10020:     }
1.194     brouard  10021:     /* End of read covariance matrix npar lines */
1.126     brouard  10022:     for(i=1; i <=npar; i++)
                   10023:       for(j=i+1;j<=npar;j++)
1.226     brouard  10024:        matcov[i][j]=matcov[j][i];
1.126     brouard  10025:     
                   10026:     if(mle==1)
                   10027:       printf("\n");
                   10028:     fprintf(ficlog,"\n");
                   10029:     
                   10030:     fflush(ficlog);
                   10031:     
                   10032:     /*-------- Rewriting parameter file ----------*/
                   10033:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   10034:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   10035:     strcat(rfileres,".");    /* */
                   10036:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10037:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  10038:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10039:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  10040:     }
                   10041:     fprintf(ficres,"#%s\n",version);
                   10042:   }    /* End of mle != -3 */
1.218     brouard  10043:   
1.186     brouard  10044:   /*  Main data
                   10045:    */
1.126     brouard  10046:   n= lastobs;
                   10047:   num=lvector(1,n);
                   10048:   moisnais=vector(1,n);
                   10049:   annais=vector(1,n);
                   10050:   moisdc=vector(1,n);
                   10051:   andc=vector(1,n);
1.220     brouard  10052:   weight=vector(1,n);
1.126     brouard  10053:   agedc=vector(1,n);
                   10054:   cod=ivector(1,n);
1.220     brouard  10055:   for(i=1;i<=n;i++){
1.234     brouard  10056:     num[i]=0;
                   10057:     moisnais[i]=0;
                   10058:     annais[i]=0;
                   10059:     moisdc[i]=0;
                   10060:     andc[i]=0;
                   10061:     agedc[i]=0;
                   10062:     cod[i]=0;
                   10063:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10064:   }
1.126     brouard  10065:   mint=matrix(1,maxwav,1,n);
                   10066:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10067:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10068:   tab=ivector(1,NCOVMAX);
1.144     brouard  10069:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10070:   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  10071: 
1.136     brouard  10072:   /* Reads data from file datafile */
                   10073:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10074:     goto end;
                   10075: 
                   10076:   /* Calculation of the number of parameters from char model */
1.234     brouard  10077:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10078:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10079:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10080:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10081:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10082:   */
                   10083:   
                   10084:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10085:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10086:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10087:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10088:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10089:   TvarF=ivector(1,NCOVMAX); /*  */
                   10090:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10091:   TvarV=ivector(1,NCOVMAX); /*  */
                   10092:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10093:   TvarA=ivector(1,NCOVMAX); /*  */
                   10094:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10095:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10096:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10097:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10098:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10099:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10100:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10101:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10102:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10103: 
1.230     brouard  10104:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10105:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10106:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10107:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10108:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10109:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10110:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10111:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10112:   */
                   10113:   /* For model-covariate k tells which data-covariate to use but
                   10114:     because this model-covariate is a construction we invent a new column
                   10115:     ncovcol + k1
                   10116:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10117:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10118:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10119:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10120:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10121:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10122:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10123:   */
1.145     brouard  10124:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10125:   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  10126:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10127:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10128:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10129:                         4 covariates (3 plus signs)
                   10130:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10131:                      */  
1.230     brouard  10132:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10133:                                * individual dummy, fixed or varying:
                   10134:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10135:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10136:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10137:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10138:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10139:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10140:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10141:                                * individual quantitative, fixed or varying:
                   10142:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10143:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10144:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10145: /* Main decodemodel */
                   10146: 
1.187     brouard  10147: 
1.223     brouard  10148:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10149:     goto end;
                   10150: 
1.137     brouard  10151:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10152:     nbwarn++;
                   10153:     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); 
                   10154:     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); 
                   10155:   }
1.136     brouard  10156:     /*  if(mle==1){*/
1.137     brouard  10157:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10158:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10159:   }
                   10160: 
                   10161:     /*-calculation of age at interview from date of interview and age at death -*/
                   10162:   agev=matrix(1,maxwav,1,imx);
                   10163: 
                   10164:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10165:     goto end;
                   10166: 
1.126     brouard  10167: 
1.136     brouard  10168:   agegomp=(int)agemin;
                   10169:   free_vector(moisnais,1,n);
                   10170:   free_vector(annais,1,n);
1.126     brouard  10171:   /* free_matrix(mint,1,maxwav,1,n);
                   10172:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10173:   /* free_vector(moisdc,1,n); */
                   10174:   /* free_vector(andc,1,n); */
1.145     brouard  10175:   /* */
                   10176:   
1.126     brouard  10177:   wav=ivector(1,imx);
1.214     brouard  10178:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10179:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10180:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10181:   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.*/
                   10182:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10183:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10184:    
                   10185:   /* Concatenates waves */
1.214     brouard  10186:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10187:      Death is a valid wave (if date is known).
                   10188:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10189:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10190:      and mw[mi+1][i]. dh depends on stepm.
                   10191:   */
                   10192: 
1.126     brouard  10193:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  10194:   /* */
                   10195:  
1.215     brouard  10196:   free_vector(moisdc,1,n);
                   10197:   free_vector(andc,1,n);
                   10198: 
1.126     brouard  10199:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10200:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10201:   ncodemax[1]=1;
1.145     brouard  10202:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10203:   cptcoveff=0;
1.220     brouard  10204:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10205:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10206:   }
                   10207:   
                   10208:   ncovcombmax=pow(2,cptcoveff);
                   10209:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10210:   for(i=1;i<ncovcombmax;i++)
                   10211:     invalidvarcomb[i]=0;
                   10212:   
1.211     brouard  10213:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10214:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10215:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10216:   
1.200     brouard  10217:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10218:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10219:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10220:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10221:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10222:    * (currently 0 or 1) in the data.
                   10223:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10224:    * corresponding modality (h,j).
                   10225:    */
                   10226: 
1.145     brouard  10227:   h=0;
                   10228:   /*if (cptcovn > 0) */
1.126     brouard  10229:   m=pow(2,cptcoveff);
                   10230:  
1.144     brouard  10231:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10232:           * For k=4 covariates, h goes from 1 to m=2**k
                   10233:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10234:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10235:           *     h\k   1     2     3     4
1.143     brouard  10236:           *______________________________  
                   10237:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10238:           *     2     2     1     1     1
                   10239:           *     3 i=2 1     2     1     1
                   10240:           *     4     2     2     1     1
                   10241:           *     5 i=3 1 i=2 1     2     1
                   10242:           *     6     2     1     2     1
                   10243:           *     7 i=4 1     2     2     1
                   10244:           *     8     2     2     2     1
1.197     brouard  10245:           *     9 i=5 1 i=3 1 i=2 1     2
                   10246:           *    10     2     1     1     2
                   10247:           *    11 i=6 1     2     1     2
                   10248:           *    12     2     2     1     2
                   10249:           *    13 i=7 1 i=4 1     2     2    
                   10250:           *    14     2     1     2     2
                   10251:           *    15 i=8 1     2     2     2
                   10252:           *    16     2     2     2     2
1.143     brouard  10253:           */
1.212     brouard  10254:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10255:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10256:      * and the value of each covariate?
                   10257:      * V1=1, V2=1, V3=2, V4=1 ?
                   10258:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10259:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10260:      * In order to get the real value in the data, we use nbcode
                   10261:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10262:      * We are keeping this crazy system in order to be able (in the future?) 
                   10263:      * to have more than 2 values (0 or 1) for a covariate.
                   10264:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10265:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10266:      *              bbbbbbbb
                   10267:      *              76543210     
                   10268:      *   h-1        00000101 (6-1=5)
1.219     brouard  10269:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10270:      *           &
                   10271:      *     1        00000001 (1)
1.219     brouard  10272:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10273:      *          +1= 00000001 =1 
1.211     brouard  10274:      *
                   10275:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10276:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10277:      *    >>k'            11
                   10278:      *          &   00000001
                   10279:      *            = 00000001
                   10280:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10281:      * Reverse h=6 and m=16?
                   10282:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10283:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10284:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10285:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10286:      * V3=decodtabm(14,3,2**4)=2
                   10287:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10288:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10289:      *          &1 000000001
                   10290:      *           = 000000001
                   10291:      *         +1= 000000010 =2
                   10292:      *                  2211
                   10293:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10294:      *                  V3=2
1.220     brouard  10295:                 * codtabm and decodtabm are identical
1.211     brouard  10296:      */
                   10297: 
1.145     brouard  10298: 
                   10299:  free_ivector(Ndum,-1,NCOVMAX);
                   10300: 
                   10301: 
1.126     brouard  10302:     
1.186     brouard  10303:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10304:   strcpy(optionfilegnuplot,optionfilefiname);
                   10305:   if(mle==-3)
1.201     brouard  10306:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10307:   strcat(optionfilegnuplot,".gp");
                   10308: 
                   10309:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10310:     printf("Problem with file %s",optionfilegnuplot);
                   10311:   }
                   10312:   else{
1.204     brouard  10313:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10314:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10315:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10316:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10317:   }
                   10318:   /*  fclose(ficgp);*/
1.186     brouard  10319: 
                   10320: 
                   10321:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10322: 
                   10323:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10324:   if(mle==-3)
1.201     brouard  10325:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10326:   strcat(optionfilehtm,".htm");
                   10327:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10328:     printf("Problem with %s \n",optionfilehtm);
                   10329:     exit(0);
1.126     brouard  10330:   }
                   10331: 
                   10332:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10333:   strcat(optionfilehtmcov,"-cov.htm");
                   10334:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10335:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10336:   }
                   10337:   else{
                   10338:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10339: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10340: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10341:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10342:   }
                   10343: 
1.213     brouard  10344:   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  10345: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10346: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10347: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10348: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10349: \n\
                   10350: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10351:  <ul><li><h4>Parameter files</h4>\n\
                   10352:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10353:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10354:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10355:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10356:  - Date and time at start: %s</ul>\n",\
                   10357:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10358:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10359:          fileres,fileres,\
                   10360:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10361:   fflush(fichtm);
                   10362: 
                   10363:   strcpy(pathr,path);
                   10364:   strcat(pathr,optionfilefiname);
1.184     brouard  10365: #ifdef WIN32
                   10366:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10367: #else
1.126     brouard  10368:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10369: #endif
                   10370:          
1.126     brouard  10371:   
1.220     brouard  10372:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10373:                 and for any valid combination of covariates
1.126     brouard  10374:      and prints on file fileres'p'. */
1.227     brouard  10375:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   10376:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10377: 
                   10378:   fprintf(fichtm,"\n");
                   10379:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10380: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10381: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10382:          imx,agemin,agemax,jmin,jmax,jmean);
                   10383:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10384:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10385:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10386:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10387:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10388: 
1.126     brouard  10389:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10390:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10391:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10392: 
                   10393:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10394:   /* For mortality only */
1.126     brouard  10395:   if (mle==-3){
1.136     brouard  10396:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  10397:                for(i=1;i<=NDIM;i++)
                   10398:                        for(j=1;j<=NDIM;j++)
                   10399:                                ximort[i][j]=0.;
1.186     brouard  10400:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10401:     cens=ivector(1,n);
                   10402:     ageexmed=vector(1,n);
                   10403:     agecens=vector(1,n);
                   10404:     dcwave=ivector(1,n);
1.223     brouard  10405:                
1.126     brouard  10406:     for (i=1; i<=imx; i++){
                   10407:       dcwave[i]=-1;
                   10408:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10409:        if (s[m][i]>nlstate) {
                   10410:          dcwave[i]=m;
                   10411:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10412:          break;
                   10413:        }
1.126     brouard  10414:     }
1.226     brouard  10415:     
1.126     brouard  10416:     for (i=1; i<=imx; i++) {
                   10417:       if (wav[i]>0){
1.226     brouard  10418:        ageexmed[i]=agev[mw[1][i]][i];
                   10419:        j=wav[i];
                   10420:        agecens[i]=1.; 
                   10421:        
                   10422:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10423:          agecens[i]=agev[mw[j][i]][i];
                   10424:          cens[i]= 1;
                   10425:        }else if (ageexmed[i]< 1) 
                   10426:          cens[i]= -1;
                   10427:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10428:          cens[i]=0 ;
1.126     brouard  10429:       }
                   10430:       else cens[i]=-1;
                   10431:     }
                   10432:     
                   10433:     for (i=1;i<=NDIM;i++) {
                   10434:       for (j=1;j<=NDIM;j++)
1.226     brouard  10435:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10436:     }
                   10437:     
1.145     brouard  10438:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10439:     /*printf("%lf %lf", p[1], p[2]);*/
                   10440:     
                   10441:     
1.136     brouard  10442: #ifdef GSL
                   10443:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10444: #else
1.126     brouard  10445:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10446: #endif
1.201     brouard  10447:     strcpy(filerespow,"POW-MORT_"); 
                   10448:     strcat(filerespow,fileresu);
1.126     brouard  10449:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10450:       printf("Problem with resultfile: %s\n", filerespow);
                   10451:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10452:     }
1.136     brouard  10453: #ifdef GSL
                   10454:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10455: #else
1.126     brouard  10456:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10457: #endif
1.126     brouard  10458:     /*  for (i=1;i<=nlstate;i++)
                   10459:        for(j=1;j<=nlstate+ndeath;j++)
                   10460:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10461:     */
                   10462:     fprintf(ficrespow,"\n");
1.136     brouard  10463: #ifdef GSL
                   10464:     /* gsl starts here */ 
                   10465:     T = gsl_multimin_fminimizer_nmsimplex;
                   10466:     gsl_multimin_fminimizer *sfm = NULL;
                   10467:     gsl_vector *ss, *x;
                   10468:     gsl_multimin_function minex_func;
                   10469: 
                   10470:     /* Initial vertex size vector */
                   10471:     ss = gsl_vector_alloc (NDIM);
                   10472:     
                   10473:     if (ss == NULL){
                   10474:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10475:     }
                   10476:     /* Set all step sizes to 1 */
                   10477:     gsl_vector_set_all (ss, 0.001);
                   10478: 
                   10479:     /* Starting point */
1.126     brouard  10480:     
1.136     brouard  10481:     x = gsl_vector_alloc (NDIM);
                   10482:     
                   10483:     if (x == NULL){
                   10484:       gsl_vector_free(ss);
                   10485:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10486:     }
                   10487:   
                   10488:     /* Initialize method and iterate */
                   10489:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10490:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10491:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10492:     gsl_vector_set(x, 0, p[1]);
                   10493:     gsl_vector_set(x, 1, p[2]);
                   10494: 
                   10495:     minex_func.f = &gompertz_f;
                   10496:     minex_func.n = NDIM;
                   10497:     minex_func.params = (void *)&p; /* ??? */
                   10498:     
                   10499:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10500:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10501:     
                   10502:     printf("Iterations beginning .....\n\n");
                   10503:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10504: 
                   10505:     iteri=0;
                   10506:     while (rval == GSL_CONTINUE){
                   10507:       iteri++;
                   10508:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10509:       
                   10510:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10511:       fflush(0);
                   10512:       
                   10513:       if (status) 
                   10514:         break;
                   10515:       
                   10516:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10517:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10518:       
                   10519:       if (rval == GSL_SUCCESS)
                   10520:         printf ("converged to a local maximum at\n");
                   10521:       
                   10522:       printf("%5d ", iteri);
                   10523:       for (it = 0; it < NDIM; it++){
                   10524:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10525:       }
                   10526:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10527:     }
                   10528:     
                   10529:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10530:     
                   10531:     gsl_vector_free(x); /* initial values */
                   10532:     gsl_vector_free(ss); /* inital step size */
                   10533:     for (it=0; it<NDIM; it++){
                   10534:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10535:       fprintf(ficrespow," %.12lf", p[it]);
                   10536:     }
                   10537:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10538: #endif
                   10539: #ifdef POWELL
                   10540:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10541: #endif  
1.126     brouard  10542:     fclose(ficrespow);
                   10543:     
1.203     brouard  10544:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10545: 
                   10546:     for(i=1; i <=NDIM; i++)
                   10547:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10548:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10549:     
                   10550:     printf("\nCovariance matrix\n ");
1.203     brouard  10551:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10552:     for(i=1; i <=NDIM; i++) {
                   10553:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10554:                                printf("%f ",matcov[i][j]);
                   10555:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10556:       }
1.203     brouard  10557:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10558:     }
                   10559:     
                   10560:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10561:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10562:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10563:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10564:     }
1.126     brouard  10565:     lsurv=vector(1,AGESUP);
                   10566:     lpop=vector(1,AGESUP);
                   10567:     tpop=vector(1,AGESUP);
                   10568:     lsurv[agegomp]=100000;
                   10569:     
                   10570:     for (k=agegomp;k<=AGESUP;k++) {
                   10571:       agemortsup=k;
                   10572:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10573:     }
                   10574:     
                   10575:     for (k=agegomp;k<agemortsup;k++)
                   10576:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10577:     
                   10578:     for (k=agegomp;k<agemortsup;k++){
                   10579:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10580:       sumlpop=sumlpop+lpop[k];
                   10581:     }
                   10582:     
                   10583:     tpop[agegomp]=sumlpop;
                   10584:     for (k=agegomp;k<(agemortsup-3);k++){
                   10585:       /*  tpop[k+1]=2;*/
                   10586:       tpop[k+1]=tpop[k]-lpop[k];
                   10587:     }
                   10588:     
                   10589:     
                   10590:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10591:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10592:       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]);
                   10593:     
                   10594:     
                   10595:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10596:                ageminpar=50;
                   10597:                agemaxpar=100;
1.194     brouard  10598:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10599:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10600: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10601: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10602:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10603: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10604: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10605:     }else{
                   10606:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10607:                        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  10608:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10609:                }
1.201     brouard  10610:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10611:                     stepm, weightopt,\
                   10612:                     model,imx,p,matcov,agemortsup);
                   10613:     
                   10614:     free_vector(lsurv,1,AGESUP);
                   10615:     free_vector(lpop,1,AGESUP);
                   10616:     free_vector(tpop,1,AGESUP);
1.220     brouard  10617:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10618:     free_ivector(cens,1,n);
                   10619:     free_vector(agecens,1,n);
                   10620:     free_ivector(dcwave,1,n);
1.220     brouard  10621: #ifdef GSL
1.136     brouard  10622: #endif
1.186     brouard  10623:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10624:   /* Standard  */
                   10625:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10626:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10627:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10628:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10629:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10630:     for (k=1; k<=npar;k++)
                   10631:       printf(" %d %8.5f",k,p[k]);
                   10632:     printf("\n");
1.205     brouard  10633:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10634:       /* mlikeli uses func not funcone */
                   10635:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10636:     }
                   10637:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10638:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10639:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10640:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10641:     }
                   10642:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10643:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10644:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10645:     for (k=1; k<=npar;k++)
                   10646:       printf(" %d %8.5f",k,p[k]);
                   10647:     printf("\n");
                   10648:     
                   10649:     /*--------- results files --------------*/
1.224     brouard  10650:     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  10651:     
                   10652:     
                   10653:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10654:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10655:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10656:     for(i=1,jk=1; i <=nlstate; i++){
                   10657:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10658:        if (k != i) {
                   10659:          printf("%d%d ",i,k);
                   10660:          fprintf(ficlog,"%d%d ",i,k);
                   10661:          fprintf(ficres,"%1d%1d ",i,k);
                   10662:          for(j=1; j <=ncovmodel; j++){
                   10663:            printf("%12.7f ",p[jk]);
                   10664:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10665:            fprintf(ficres,"%12.7f ",p[jk]);
                   10666:            jk++; 
                   10667:          }
                   10668:          printf("\n");
                   10669:          fprintf(ficlog,"\n");
                   10670:          fprintf(ficres,"\n");
                   10671:        }
1.126     brouard  10672:       }
                   10673:     }
1.203     brouard  10674:     if(mle != 0){
                   10675:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10676:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10677:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10678:       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");
                   10679:       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");
                   10680:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10681:        for(k=1; k <=(nlstate+ndeath); k++){
                   10682:          if (k != i) {
                   10683:            printf("%d%d ",i,k);
                   10684:            fprintf(ficlog,"%d%d ",i,k);
                   10685:            for(j=1; j <=ncovmodel; j++){
                   10686:              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]));
                   10687:              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]));
                   10688:              jk++; 
                   10689:            }
                   10690:            printf("\n");
                   10691:            fprintf(ficlog,"\n");
                   10692:          }
                   10693:        }
1.193     brouard  10694:       }
1.203     brouard  10695:     } /* end of hesscov and Wald tests */
1.225     brouard  10696:     
1.203     brouard  10697:     /*  */
1.126     brouard  10698:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10699:     printf("# Scales (for hessian or gradient estimation)\n");
                   10700:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10701:     for(i=1,jk=1; i <=nlstate; i++){
                   10702:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10703:        if (j!=i) {
                   10704:          fprintf(ficres,"%1d%1d",i,j);
                   10705:          printf("%1d%1d",i,j);
                   10706:          fprintf(ficlog,"%1d%1d",i,j);
                   10707:          for(k=1; k<=ncovmodel;k++){
                   10708:            printf(" %.5e",delti[jk]);
                   10709:            fprintf(ficlog," %.5e",delti[jk]);
                   10710:            fprintf(ficres," %.5e",delti[jk]);
                   10711:            jk++;
                   10712:          }
                   10713:          printf("\n");
                   10714:          fprintf(ficlog,"\n");
                   10715:          fprintf(ficres,"\n");
                   10716:        }
1.126     brouard  10717:       }
                   10718:     }
                   10719:     
                   10720:     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  10721:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10722:       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");
                   10723:     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");
                   10724:     /* # 121 Var(a12)\n\ */
                   10725:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10726:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10727:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10728:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10729:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10730:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10731:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10732:     
                   10733:     
                   10734:     /* Just to have a covariance matrix which will be more understandable
                   10735:        even is we still don't want to manage dictionary of variables
                   10736:     */
                   10737:     for(itimes=1;itimes<=2;itimes++){
                   10738:       jj=0;
                   10739:       for(i=1; i <=nlstate; i++){
1.225     brouard  10740:        for(j=1; j <=nlstate+ndeath; j++){
                   10741:          if(j==i) continue;
                   10742:          for(k=1; k<=ncovmodel;k++){
                   10743:            jj++;
                   10744:            ca[0]= k+'a'-1;ca[1]='\0';
                   10745:            if(itimes==1){
                   10746:              if(mle>=1)
                   10747:                printf("#%1d%1d%d",i,j,k);
                   10748:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10749:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10750:            }else{
                   10751:              if(mle>=1)
                   10752:                printf("%1d%1d%d",i,j,k);
                   10753:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10754:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10755:            }
                   10756:            ll=0;
                   10757:            for(li=1;li <=nlstate; li++){
                   10758:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10759:                if(lj==li) continue;
                   10760:                for(lk=1;lk<=ncovmodel;lk++){
                   10761:                  ll++;
                   10762:                  if(ll<=jj){
                   10763:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10764:                    if(ll<jj){
                   10765:                      if(itimes==1){
                   10766:                        if(mle>=1)
                   10767:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10768:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10769:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10770:                      }else{
                   10771:                        if(mle>=1)
                   10772:                          printf(" %.5e",matcov[jj][ll]); 
                   10773:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10774:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10775:                      }
                   10776:                    }else{
                   10777:                      if(itimes==1){
                   10778:                        if(mle>=1)
                   10779:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10780:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10781:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10782:                      }else{
                   10783:                        if(mle>=1)
                   10784:                          printf(" %.7e",matcov[jj][ll]); 
                   10785:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10786:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10787:                      }
                   10788:                    }
                   10789:                  }
                   10790:                } /* end lk */
                   10791:              } /* end lj */
                   10792:            } /* end li */
                   10793:            if(mle>=1)
                   10794:              printf("\n");
                   10795:            fprintf(ficlog,"\n");
                   10796:            fprintf(ficres,"\n");
                   10797:            numlinepar++;
                   10798:          } /* end k*/
                   10799:        } /*end j */
1.126     brouard  10800:       } /* end i */
                   10801:     } /* end itimes */
                   10802:     
                   10803:     fflush(ficlog);
                   10804:     fflush(ficres);
1.225     brouard  10805:     while(fgets(line, MAXLINE, ficpar)) {
                   10806:       /* If line starts with a # it is a comment */
                   10807:       if (line[0] == '#') {
                   10808:        numlinepar++;
                   10809:        fputs(line,stdout);
                   10810:        fputs(line,ficparo);
                   10811:        fputs(line,ficlog);
                   10812:        continue;
                   10813:       }else
                   10814:        break;
                   10815:     }
                   10816:     
1.209     brouard  10817:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10818:     /*   ungetc(c,ficpar); */
                   10819:     /*   fgets(line, MAXLINE, ficpar); */
                   10820:     /*   fputs(line,stdout); */
                   10821:     /*   fputs(line,ficparo); */
                   10822:     /* } */
                   10823:     /* ungetc(c,ficpar); */
1.126     brouard  10824:     
                   10825:     estepm=0;
1.209     brouard  10826:     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  10827:       
                   10828:       if (num_filled != 6) {
                   10829:        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);
                   10830:        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);
                   10831:        goto end;
                   10832:       }
                   10833:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10834:     }
                   10835:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10836:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10837:     
1.209     brouard  10838:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10839:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10840:     if (fage <= 2) {
                   10841:       bage = ageminpar;
                   10842:       fage = agemaxpar;
                   10843:     }
                   10844:     
                   10845:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10846:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10847:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10848:                
1.186     brouard  10849:     /* Other stuffs, more or less useful */    
1.126     brouard  10850:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10851:       ungetc(c,ficpar);
                   10852:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10853:       fputs(line,stdout);
1.126     brouard  10854:       fputs(line,ficparo);
                   10855:     }
                   10856:     ungetc(c,ficpar);
                   10857:     
                   10858:     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
                   10859:     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);
                   10860:     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);
                   10861:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10862:     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);
                   10863:     
                   10864:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10865:       ungetc(c,ficpar);
                   10866:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10867:       fputs(line,stdout);
1.126     brouard  10868:       fputs(line,ficparo);
                   10869:     }
                   10870:     ungetc(c,ficpar);
                   10871:     
                   10872:     
                   10873:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10874:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10875:     
                   10876:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10877:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10878:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10879:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10880:     
                   10881:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10882:       ungetc(c,ficpar);
                   10883:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10884:       fputs(line,stdout);
1.238     brouard  10885:       fputs(line,ficres);
1.126     brouard  10886:       fputs(line,ficparo);
                   10887:     }
                   10888:     ungetc(c,ficpar);
                   10889:     
                   10890:     fscanf(ficpar,"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);
                   10891:     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);
                   10892:     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);
                   10893:     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);
                   10894:     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);
                   10895:     /* day and month of proj2 are not used but only year anproj2.*/
                   10896:     
1.217     brouard  10897:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10898:       ungetc(c,ficpar);
                   10899:       fgets(line, MAXLINE, ficpar);
                   10900:       fputs(line,stdout);
                   10901:       fputs(line,ficparo);
1.238     brouard  10902:       fputs(line,ficres);
1.217     brouard  10903:     }
                   10904:     ungetc(c,ficpar);
                   10905:     
                   10906:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
1.223     brouard  10907:     fprintf(ficparo,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   10908:     fprintf(ficlog,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   10909:     fprintf(ficres,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
1.217     brouard  10910:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10911:     
1.230     brouard  10912:     /* Results */
1.235     brouard  10913:     nresult=0;
1.230     brouard  10914:     while(fgets(line, MAXLINE, ficpar)) {
                   10915:       /* If line starts with a # it is a comment */
                   10916:       if (line[0] == '#') {
                   10917:        numlinepar++;
                   10918:        fputs(line,stdout);
                   10919:        fputs(line,ficparo);
                   10920:        fputs(line,ficlog);
1.238     brouard  10921:        fputs(line,ficres);
1.230     brouard  10922:        continue;
                   10923:       }else
                   10924:        break;
                   10925:     }
1.240     brouard  10926:     if (!feof(ficpar))
1.230     brouard  10927:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
1.240     brouard  10928:       if (num_filled == 0){
1.230     brouard  10929:        resultline[0]='\0';
1.240     brouard  10930:       break;
                   10931:       } else if (num_filled != 1){
1.230     brouard  10932:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10933:       }
1.235     brouard  10934:       nresult++; /* Sum of resultlines */
                   10935:       printf("Result %d: result=%s\n",nresult, resultline);
                   10936:       if(nresult > MAXRESULTLINES){
                   10937:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10938:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10939:        goto end;
                   10940:       }
                   10941:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238     brouard  10942:       fprintf(ficparo,"result: %s\n",resultline);
                   10943:       fprintf(ficres,"result: %s\n",resultline);
                   10944:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  10945:       while(fgets(line, MAXLINE, ficpar)) {
                   10946:        /* If line starts with a # it is a comment */
                   10947:        if (line[0] == '#') {
                   10948:          numlinepar++;
                   10949:          fputs(line,stdout);
                   10950:          fputs(line,ficparo);
1.238     brouard  10951:          fputs(line,ficres);
1.230     brouard  10952:          fputs(line,ficlog);
                   10953:          continue;
                   10954:        }else
                   10955:          break;
                   10956:       }
                   10957:       if (feof(ficpar))
                   10958:        break;
                   10959:       else{ /* Processess output results for this combination of covariate values */
                   10960:       }                                   
1.240     brouard  10961:     } /* end while */
1.230     brouard  10962: 
                   10963: 
1.126     brouard  10964:     
1.230     brouard  10965:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  10966:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  10967:     
                   10968:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  10969:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  10970:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10971: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10972: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  10973:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10974: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10975: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10976:     }else{
1.218     brouard  10977:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  10978:     }
                   10979:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  10980:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   10981:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  10982:                
1.225     brouard  10983:     /*------------ free_vector  -------------*/
                   10984:     /*  chdir(path); */
1.220     brouard  10985:                
1.215     brouard  10986:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   10987:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   10988:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   10989:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  10990:     free_lvector(num,1,n);
                   10991:     free_vector(agedc,1,n);
                   10992:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   10993:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   10994:     fclose(ficparo);
                   10995:     fclose(ficres);
1.220     brouard  10996:                
                   10997:                
1.186     brouard  10998:     /* Other results (useful)*/
1.220     brouard  10999:                
                   11000:                
1.126     brouard  11001:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  11002:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   11003:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  11004:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  11005:     fclose(ficrespl);
                   11006: 
                   11007:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  11008:     /*#include "hpijx.h"*/
                   11009:     hPijx(p, bage, fage);
1.145     brouard  11010:     fclose(ficrespij);
1.227     brouard  11011:     
1.220     brouard  11012:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  11013:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  11014:     k=1;
1.126     brouard  11015:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  11016:     
1.219     brouard  11017:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  11018:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  11019:     for(i=1;i<=AGESUP;i++)
1.219     brouard  11020:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  11021:        for(k=1;k<=ncovcombmax;k++)
                   11022:          probs[i][j][k]=0.;
1.219     brouard  11023:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   11024:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   11025:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  11026:       for(i=1;i<=AGESUP;i++)
                   11027:        for(j=1;j<=nlstate;j++)
                   11028:          for(k=1;k<=ncovcombmax;k++)
                   11029:            mobaverages[i][j][k]=0.;
1.219     brouard  11030:       mobaverage=mobaverages;
                   11031:       if (mobilav!=0) {
1.235     brouard  11032:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  11033:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   11034:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   11035:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   11036:        }
1.219     brouard  11037:       }
                   11038:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   11039:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11040:       else if (mobilavproj !=0) {
1.235     brouard  11041:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  11042:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   11043:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11044:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11045:        }
1.219     brouard  11046:       }
                   11047:     }/* end if moving average */
1.227     brouard  11048:     
1.126     brouard  11049:     /*---------- Forecasting ------------------*/
                   11050:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   11051:     if(prevfcast==1){
                   11052:       /*    if(stepm ==1){*/
1.225     brouard  11053:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11054:     }
1.217     brouard  11055:     if(backcast==1){
1.219     brouard  11056:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11057:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11058:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11059: 
                   11060:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11061: 
                   11062:       bprlim=matrix(1,nlstate,1,nlstate);
                   11063:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11064:       fclose(ficresplb);
                   11065: 
1.222     brouard  11066:       hBijx(p, bage, fage, mobaverage);
                   11067:       fclose(ficrespijb);
1.219     brouard  11068:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11069: 
                   11070:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11071:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11072:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11073:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11074:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11075:     }
1.217     brouard  11076:     
1.186     brouard  11077:  
                   11078:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11079: 
1.215     brouard  11080:     free_ivector(wav,1,imx);
                   11081:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11082:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11083:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11084:                
                   11085:                
1.127     brouard  11086:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11087:                
1.201     brouard  11088:     strcpy(filerese,"E_");
                   11089:     strcat(filerese,fileresu);
1.126     brouard  11090:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11091:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11092:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11093:     }
1.208     brouard  11094:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11095:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11096: 
                   11097:     pstamp(ficreseij);
1.219     brouard  11098:                
1.235     brouard  11099:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11100:     if (cptcovn < 1){i1=1;}
                   11101:     
                   11102:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11103:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11104:       if(TKresult[nres]!= k)
                   11105:        continue;
1.219     brouard  11106:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11107:       printf("\n#****** ");
1.225     brouard  11108:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11109:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11110:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11111:       }
                   11112:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11113:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11114:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11115:       }
                   11116:       fprintf(ficreseij,"******\n");
1.235     brouard  11117:       printf("******\n");
1.219     brouard  11118:       
                   11119:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11120:       oldm=oldms;savm=savms;
1.235     brouard  11121:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11122:       
1.219     brouard  11123:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11124:     }
                   11125:     fclose(ficreseij);
1.208     brouard  11126:     printf("done evsij\n");fflush(stdout);
                   11127:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11128:                
1.227     brouard  11129:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11130:                
                   11131:                
1.201     brouard  11132:     strcpy(filerest,"T_");
                   11133:     strcat(filerest,fileresu);
1.127     brouard  11134:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11135:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11136:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11137:     }
1.208     brouard  11138:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11139:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11140:                
1.126     brouard  11141: 
1.201     brouard  11142:     strcpy(fileresstde,"STDE_");
                   11143:     strcat(fileresstde,fileresu);
1.126     brouard  11144:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11145:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11146:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11147:     }
1.227     brouard  11148:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11149:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11150: 
1.201     brouard  11151:     strcpy(filerescve,"CVE_");
                   11152:     strcat(filerescve,fileresu);
1.126     brouard  11153:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11154:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11155:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11156:     }
1.227     brouard  11157:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11158:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11159: 
1.201     brouard  11160:     strcpy(fileresv,"V_");
                   11161:     strcat(fileresv,fileresu);
1.126     brouard  11162:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11163:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11164:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11165:     }
1.227     brouard  11166:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11167:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11168: 
1.145     brouard  11169:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11170:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11171:           
1.235     brouard  11172:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11173:     if (cptcovn < 1){i1=1;}
                   11174:     
                   11175:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11176:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11177:       if(TKresult[nres]!= k)
                   11178:        continue;
1.242   ! brouard  11179:       printf("\n#****** Result for:");
        !          11180:       fprintf(ficrest,"\n#****** Result for:");
        !          11181:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  11182:       for(j=1;j<=cptcoveff;j++){ 
                   11183:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11184:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11185:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11186:       }
1.235     brouard  11187:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11188:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11189:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11190:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11191:       }        
1.208     brouard  11192:       fprintf(ficrest,"******\n");
1.227     brouard  11193:       fprintf(ficlog,"******\n");
                   11194:       printf("******\n");
1.208     brouard  11195:       
                   11196:       fprintf(ficresstdeij,"\n#****** ");
                   11197:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11198:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11199:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11200:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11201:       }
1.235     brouard  11202:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11203:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11204:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11205:       }        
1.208     brouard  11206:       fprintf(ficresstdeij,"******\n");
                   11207:       fprintf(ficrescveij,"******\n");
                   11208:       
                   11209:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11210:       /* pstamp(ficresvij); */
1.225     brouard  11211:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11212:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11213:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11214:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11215:       }        
1.208     brouard  11216:       fprintf(ficresvij,"******\n");
                   11217:       
                   11218:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11219:       oldm=oldms;savm=savms;
1.235     brouard  11220:       printf(" cvevsij ");
                   11221:       fprintf(ficlog, " cvevsij ");
                   11222:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11223:       printf(" end cvevsij \n ");
                   11224:       fprintf(ficlog, " end cvevsij \n ");
                   11225:       
                   11226:       /*
                   11227:        */
                   11228:       /* goto endfree; */
                   11229:       
                   11230:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11231:       pstamp(ficrest);
                   11232:       
                   11233:       
                   11234:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11235:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11236:        cptcod= 0; /* To be deleted */
                   11237:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11238:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11239:        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  11240:        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 ");
                   11241:        if(vpopbased==1)
                   11242:          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);
                   11243:        else
                   11244:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11245:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11246:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11247:        fprintf(ficrest,"\n");
                   11248:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11249:        epj=vector(1,nlstate+1);
                   11250:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11251:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11252:        for(age=bage; age <=fage ;age++){
1.235     brouard  11253:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11254:          if (vpopbased==1) {
                   11255:            if(mobilav ==0){
                   11256:              for(i=1; i<=nlstate;i++)
                   11257:                prlim[i][i]=probs[(int)age][i][k];
                   11258:            }else{ /* mobilav */ 
                   11259:              for(i=1; i<=nlstate;i++)
                   11260:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11261:            }
                   11262:          }
1.219     brouard  11263:          
1.227     brouard  11264:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11265:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11266:          /* printf(" age %4.0f ",age); */
                   11267:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11268:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11269:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11270:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11271:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11272:            }
                   11273:            epj[nlstate+1] +=epj[j];
                   11274:          }
                   11275:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11276:          
1.227     brouard  11277:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11278:            for(j=1;j <=nlstate;j++)
                   11279:              vepp += vareij[i][j][(int)age];
                   11280:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11281:          for(j=1;j <=nlstate;j++){
                   11282:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11283:          }
                   11284:          fprintf(ficrest,"\n");
                   11285:        }
1.208     brouard  11286:       } /* End vpopbased */
                   11287:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11288:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11289:       free_vector(epj,1,nlstate+1);
1.235     brouard  11290:       printf("done selection\n");fflush(stdout);
                   11291:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11292:       
1.145     brouard  11293:       /*}*/
1.235     brouard  11294:     } /* End k selection */
1.227     brouard  11295: 
                   11296:     printf("done State-specific expectancies\n");fflush(stdout);
                   11297:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11298: 
1.126     brouard  11299:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11300:     
1.201     brouard  11301:     strcpy(fileresvpl,"VPL_");
                   11302:     strcat(fileresvpl,fileresu);
1.126     brouard  11303:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11304:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11305:       exit(0);
                   11306:     }
1.208     brouard  11307:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11308:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11309:     
1.145     brouard  11310:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11311:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11312:     
1.235     brouard  11313:     i1=pow(2,cptcoveff);
                   11314:     if (cptcovn < 1){i1=1;}
                   11315: 
                   11316:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11317:     for(k=1; k<=i1;k++){
                   11318:       if(TKresult[nres]!= k)
                   11319:        continue;
1.227     brouard  11320:       fprintf(ficresvpl,"\n#****** ");
                   11321:       printf("\n#****** ");
                   11322:       fprintf(ficlog,"\n#****** ");
                   11323:       for(j=1;j<=cptcoveff;j++) {
                   11324:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11325:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11326:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11327:       }
1.235     brouard  11328:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11329:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11330:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11331:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11332:       }        
1.227     brouard  11333:       fprintf(ficresvpl,"******\n");
                   11334:       printf("******\n");
                   11335:       fprintf(ficlog,"******\n");
                   11336:       
                   11337:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11338:       oldm=oldms;savm=savms;
1.235     brouard  11339:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11340:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11341:       /*}*/
1.126     brouard  11342:     }
1.227     brouard  11343:     
1.126     brouard  11344:     fclose(ficresvpl);
1.208     brouard  11345:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11346:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11347:     
                   11348:     free_vector(weight,1,n);
                   11349:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11350:     free_imatrix(s,1,maxwav+1,1,n);
                   11351:     free_matrix(anint,1,maxwav,1,n); 
                   11352:     free_matrix(mint,1,maxwav,1,n);
                   11353:     free_ivector(cod,1,n);
                   11354:     free_ivector(tab,1,NCOVMAX);
                   11355:     fclose(ficresstdeij);
                   11356:     fclose(ficrescveij);
                   11357:     fclose(ficresvij);
                   11358:     fclose(ficrest);
                   11359:     fclose(ficpar);
                   11360:     
                   11361:     
1.126     brouard  11362:     /*---------- End : free ----------------*/
1.219     brouard  11363:     if (mobilav!=0 ||mobilavproj !=0)
                   11364:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
1.218     brouard  11365:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11366:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11367:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11368:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11369:   /* endfree:*/
                   11370:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11371:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11372:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11373:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11374:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11375:   free_matrix(coqvar,1,maxwav,1,n);
                   11376:   free_matrix(covar,0,NCOVMAX,1,n);
                   11377:   free_matrix(matcov,1,npar,1,npar);
                   11378:   free_matrix(hess,1,npar,1,npar);
                   11379:   /*free_vector(delti,1,npar);*/
                   11380:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11381:   free_matrix(agev,1,maxwav,1,imx);
                   11382:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11383:   
                   11384:   free_ivector(ncodemax,1,NCOVMAX);
                   11385:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11386:   free_ivector(Dummy,-1,NCOVMAX);
                   11387:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11388:   free_ivector(DummyV,1,NCOVMAX);
                   11389:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11390:   free_ivector(Typevar,-1,NCOVMAX);
                   11391:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11392:   free_ivector(TvarsQ,1,NCOVMAX);
                   11393:   free_ivector(TvarsQind,1,NCOVMAX);
                   11394:   free_ivector(TvarsD,1,NCOVMAX);
                   11395:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11396:   free_ivector(TvarFD,1,NCOVMAX);
                   11397:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11398:   free_ivector(TvarF,1,NCOVMAX);
                   11399:   free_ivector(TvarFind,1,NCOVMAX);
                   11400:   free_ivector(TvarV,1,NCOVMAX);
                   11401:   free_ivector(TvarVind,1,NCOVMAX);
                   11402:   free_ivector(TvarA,1,NCOVMAX);
                   11403:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11404:   free_ivector(TvarFQ,1,NCOVMAX);
                   11405:   free_ivector(TvarFQind,1,NCOVMAX);
                   11406:   free_ivector(TvarVD,1,NCOVMAX);
                   11407:   free_ivector(TvarVDind,1,NCOVMAX);
                   11408:   free_ivector(TvarVQ,1,NCOVMAX);
                   11409:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11410:   free_ivector(Tvarsel,1,NCOVMAX);
                   11411:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11412:   free_ivector(Tposprod,1,NCOVMAX);
                   11413:   free_ivector(Tprod,1,NCOVMAX);
                   11414:   free_ivector(Tvaraff,1,NCOVMAX);
                   11415:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11416:   free_ivector(Tage,1,NCOVMAX);
                   11417:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11418:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11419:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11420:   
                   11421:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11422:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11423:   fflush(fichtm);
                   11424:   fflush(ficgp);
                   11425:   
1.227     brouard  11426:   
1.126     brouard  11427:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11428:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11429:     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  11430:   }else{
                   11431:     printf("End of Imach\n");
                   11432:     fprintf(ficlog,"End of Imach\n");
                   11433:   }
                   11434:   printf("See log file on %s\n",filelog);
                   11435:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11436:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11437:   rend_time = time(NULL);  
                   11438:   end_time = *localtime(&rend_time);
                   11439:   /* tml = *localtime(&end_time.tm_sec); */
                   11440:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11441:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11442:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11443:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11444:   
1.157     brouard  11445:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11446:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11447:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11448:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11449: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11450:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11451:   fclose(fichtm);
                   11452:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11453:   fclose(fichtmcov);
                   11454:   fclose(ficgp);
                   11455:   fclose(ficlog);
                   11456:   /*------ End -----------*/
1.227     brouard  11457:   
                   11458:   
                   11459:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11460: #ifdef WIN32
1.227     brouard  11461:   if (_chdir(pathcd) != 0)
                   11462:     printf("Can't move to directory %s!\n",path);
                   11463:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11464: #else
1.227     brouard  11465:     if(chdir(pathcd) != 0)
                   11466:       printf("Can't move to directory %s!\n", path);
                   11467:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11468: #endif 
1.126     brouard  11469:     printf("Current directory %s!\n",pathcd);
                   11470:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11471:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11472: #ifdef _WIN32
1.126     brouard  11473:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11474: #endif
                   11475:   if(!stat(plotcmd,&info)){
1.158     brouard  11476:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11477:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11478:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11479:     }else
                   11480:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11481: #ifdef __unix
1.126     brouard  11482:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11483:     if(!stat(plotcmd,&info)){
1.158     brouard  11484:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11485:     }else
                   11486:       strcpy(pplotcmd,plotcmd);
                   11487: #endif
                   11488:   }else
                   11489:     strcpy(pplotcmd,plotcmd);
                   11490:   
                   11491:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11492:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11493:   
1.126     brouard  11494:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11495:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11496:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11497:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11498:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11499:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11500:   }
1.158     brouard  11501:   printf(" Successful, please wait...");
1.126     brouard  11502:   while (z[0] != 'q') {
                   11503:     /* chdir(path); */
1.154     brouard  11504:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11505:     scanf("%s",z);
                   11506: /*     if (z[0] == 'c') system("./imach"); */
                   11507:     if (z[0] == 'e') {
1.158     brouard  11508: #ifdef __APPLE__
1.152     brouard  11509:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11510: #elif __linux
                   11511:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11512: #else
1.152     brouard  11513:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11514: #endif
                   11515:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11516:       system(pplotcmd);
1.126     brouard  11517:     }
                   11518:     else if (z[0] == 'g') system(plotcmd);
                   11519:     else if (z[0] == 'q') exit(0);
                   11520:   }
1.227     brouard  11521: end:
1.126     brouard  11522:   while (z[0] != 'q') {
1.195     brouard  11523:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11524:     scanf("%s",z);
                   11525:   }
                   11526: }

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